0
votes

How Do I convert a datetime from mm/dd/yyyy to dd MMM yyyy? DateTime.ParseExact or DateTime.TryParseExact does not require a parameter that tells it what format I want it in. So how does it know that I want it to return the passed in date to dd MMM yyyy format?

DateTime result;
var dateTime = DateTime.TryParseExact("03/21/2013", "mm/dd/yyyy",CultureInfo.InvariantCulture,DateTimeStyles.None, out result);
2
Your dateTime variable there is a boolean - the TryParseExact method returns a boolean indicating whether or not the parsing was successful. Assuming it's successful, the value will be stored in your result variable. - Joe Enos
Oh, and lower case 'm' is for minute, not month, so your parse statement needs to have "MM/dd/yyyy", or more correctly "MM\\/dd\\/yyyy" (the backslash escapes out the forward slash so the system knows that it's a true forward-slash and not a special character represented by a forward-slash - it's complicated, but definitely use the backslash). (Oh, and the two backslashes are because it's a C# escape character, so it's really only one). - Joe Enos

2 Answers

7
votes

The DateTime object you get back has no formatting - it's just the raw date and time. To convert it to your new format after you've got it in a DateTime object, you call ToString on it, like:

string formattedDate = result.ToString("dd MMM yyyy");
1
votes

A DateTime object does not store the date in string format. Rather you may output the value of DateTime using the format you like when obtaining a string representation:

// assuming you have date DateTime object variable named dateTime
dateTime.ToString("dd MMM yyyyy");