-2

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.

Sparrow
  • 355
  • 4
  • 19
  • What do you mean by "which is of date type"? There's no type in the .NET BCL which would represent "quarter 2 2016" as far as I'm aware. (Such a type wouldn't be called `Date` ideally anyway, as a quarter isn't a date...) – Jon Skeet Jun 10 '16 at 07:56
  • I mean date which can be represented as a quarter. – Sparrow Jun 10 '16 at 07:59
  • But a quarter *isn't* a date. That's like saying "The range 1-10 is an integer." And which type do you mean? Or are you asking if there *is* such a type in .NET? (There isn't, as far as I'm aware, but you could create your own.) – Jon Skeet Jun 10 '16 at 08:00
  • DateTime struct of course doesn't have quarters like SQL has, however you can create a method that returning amount of quarter in certain year based from month digit range as string. – Tetsuya Yamamoto Jun 10 '16 at 08:03

1 Answers1

1

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
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939