Search code examples
c#datetimedate-conversion

Convert a MMM yyyy string date to a DateTime value without a massive nested if using c#?


I have an incoming string variable called strDate that's formatted with the first three characters of the month and a four character year, like this: "Jul 2017".

I need to convert that string to a date formatted like this: "7/1/2017". I'm wondering if there's a better way to do this than creating a massive nested if along the pattern shown below to account for all 12 months. I hate repeating code. Can anyone make a suggestion?

string strDate = "Jul 2017";
string strNewDate = "";

if (strDate.Substring(0,3) == "Jul")
{
    string strMonth = "7";
    strNewDate = strMonth + "/1/";
    strNewDate = strNewDate + strDate.Substring(4, 4);
    DateTime newDate = Convert.ToDateTime(strNewDate);
}

Solution

  • You just need to do a DateTime.TryParse():

    string input = "Jul 2017";      
    DateTime newDateTime;
    if(DateTime.TryParse(input, out newDateTime ))
    {
        //newDateTime was parsed successfully
    }
    

    Your format ("MMM yyyy") is a standard format that C# recognizes to it should parse fine. However there is the DateTime.TryParseExact method that lets you specify the exact format you are expecting the string to be in.