todd.pund
todd.pund

Reputation: 689

Parsing a string to DateTime, formatting, then back to string - C#

I'm pulling a date/time from a MS SQL Server 2008 db and trying to format the date to show just the date in "dd/MM/yyyy" format.

The data in the DB looks like this:

2011-05-04 15:50:00.000

The unformatted string when displayed appears as this:

5/25/2011 8:47:00 AM

Yet this code fails when I try to parse it to the correct format:

DateTime dateA = DateTime.ParseExact(curShopDate, "ddMMyyyy", System.Globalization.CultureInfo.InvariantCulture);
curShopDate = dateA.ToString();

I also tried this code, trying to split just the date portion away from the time:

string[] stringA = curShopDate.Split(' ');
DateTime dateA = DateTime.ParseExact(stringA[0], "ddMMyyyy", System.Globalization.CultureInfo.InvariantCulture);
curShopDate = dateA.ToString();

Both versions crashed with an "String was not recognized as a valid DateTime." error.

Upvotes: 1

Views: 2424

Answers (3)

James Hill
James Hill

Reputation: 61842

The issue is with your format parameter. Your string is not in the ddMMyyyy format, it's in the M/dd/yyyy format:

string curShopDate = "5/25/2011 8:47:00 AM";
DateTime dateA = DateTime.ParseExact(curShopDate.Split(' ')[0], "M/dd/yyyy",
                              System.Globalization.CultureInfo.InvariantCulture);

You could also parse the string without stripping the time from the date:

string curShopDate = "5/25/2011 8:47:00 AM";
DateTime dateA = DateTime.ParseExact(curShopDate, "M/dd/yyyy h:mm:ss tt", 
                              System.Globalization.CultureInfo.InvariantCulture);

Upvotes: 4

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112672

If you use ParseExact, then you must specify the exact format: "M/d/yyyy h:mm:ss tt", which matches your date string "5/25/2011 8:47:00 AM".

You can take the date component of a date/time with:

DateTime dateTime = DateTime.Now;
DateTime dateOnly = dateTime.Date;

Upvotes: 0

hawkke
hawkke

Reputation: 4262

According to MSDN:

The DateTime.ParseExact(String, String, IFormatProvider) method parses the string representation of a date, which must be in the format defined by the format parameter. It also requires that the and elements of the string representation of a date and time appear in the order specified by format, and that s have no white space other than that permitted by format.

So, if I'm reading that correctly, you specified the format as "ddMMyyyy" but your string is in "M/dd/yyyy h:mm:ss tt". Try either changing your format to "M/dd/yyyy h:mm:ss tt" or switch to DateTime.TryParse().

Upvotes: 2

Related Questions