novato novato - 3 months ago 9
C# Question

Convert to a complete date in c#

I have the date in this format:

MMyyyy
.

I need convert to the format:
yyyyMMdd


I tried this:

DateTime.TryParseExact(monthyear, "yyyyMMdd", CultureInfo.InvariantCulture,
DateTimeStyles.None, out date);


Did not work.

Answer

In .NET DateTime string formats, mm stands for minutes and MM stands for month. Also, the format you pass to the Parse is the existing format and not the output format. So you should use:

DateTime.TryParseExact(monthyear, "MMyyyy", CultureInfo.InvariantCulture, 
                DateTimeStyles.None, out date);

string result = date.ToString("yyyyMMdd");

So you're asking the API to Convert a String which is in the "MMyyyy" format to a DateTime object. Then you use the DateTime's .ToString() method to convert it to the desired string representation format which is "yyyyMMdd".

The Day part of the DateTime would be default to the first day of the month since it is not provided in your string representation.