B. Clay Shannon B. Clay Shannon - 1 month ago 7
C# Question

How can I convert a string in the format "YYYYMM" to "MMMYY"?

I want to pass values in YYYYMM format such as "201509" to a function and retrieve the human-friendlier "MMMYY" format, such as "Sep 2015".

I thought this might work:

internal static string GetMMMYYFromYYYYMM(String YYYYMMVal)
{
string intermediateStr = YYYYMMVal + "01";
DateTime intermediateDate = Convert.ToDateTime(intermediateStr);
return intermediateDate.ToString("MMMyy");
}


...but no, it crashes with "String was not recognized as a valid DateTime"

ISTM that the YYYYMMDD format should be grokkable and convertible to a DateTime. What do I need to change?

Answer

You should use DateTime.ParseExact. So your code will look like this:

internal static string GetMMMYYFromYYYYMM(String YYYYMMVal)
{
    DateTime intermediateDate = DateTime.ParseExact(YYYYMMVal, "yyyyMM", CultureInfo.InvariantCulture);

    return intermediateDate.ToString("MMMyy");
}