Search code examples
c#stringdatedate-conversion

Convert string to date c#


I want to convert below string to Date type in c#,

"Q2(JUN)-2016" 
     to
 Q2-2016 (which is of date type)

The result should be of date type and it should indicate quarter2.


Solution

  • You could first parse it to DateTime and then use a simple calculation to get the quarter:

    string quarterInfo = "Q2(JUN) - 2016";
    DateTime monthDt;  // will be parsed to: 06/01/2016 00:00:00
    if (DateTime.TryParseExact(
        quarterInfo.Substring(quarterInfo.IndexOf('(') + 1), 
        "MMM) - yyyy",
        DateTimeFormatInfo.InvariantInfo,
        DateTimeStyles.None, 
        out monthDt))
    {
        int year = monthDt.Year;
        int quarter = (monthDt.Month + 2) / 3;
        Console.WriteLine("Q{0}-{1}", quarter, year);  // Q2-2016
    }