0

I need transform this input string june 2014 in 2014-06 output date and I tried this solution:

DateTime dt;
DateTime.TryParseExact(Input.ToString(), "MMM yyyy", 
                       CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);

Response.Write(dt.ToString("yyyy MMM"));

But in output I have 0001 jan , why?

I would greatly appreciate any help you can give me in working this problem.

Thank you in advance.

Hamamelis
  • 1,983
  • 8
  • 27
  • 41
  • Refer `James Curran's` answer from this question http://stackoverflow.com/questions/258793/how-to-parse-a-month-name-string-to-an-integer-for-comparison-in-c – Earth Aug 05 '14 at 10:23
  • 1
    Just to be clear, the reason why it outputs `0001 jan` is because the parse fails, and the function is designed to return `DateTime.Min` if the parse fails – musefan Aug 05 '14 at 10:27

2 Answers2

7

Your format string should be "MMMM yyyy" for input in the format "june 2014", and "yyyy-MM" for output in the format "2014-06":

DateTime dt = new DateTime();
bool parseResult = DateTime.TryParseExact(Input.ToString(), "MMMM yyyy", 
                   CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);

if(parseResult)
{
 Response.Write(dt.ToString("yyyy-MM"));
}
else
{
 //Error message about parse fail perhaps?
}
  • "MMM" is for the 3 letter version such as Jun or Sep.
  • "MMMM" is for the full month name such as June or September
  • "MM" is for the numeric representation such as 06 or 09.
shree.pat18
  • 21,449
  • 3
  • 43
  • 63
  • 2
    You're not going to check if the `TryParse` was successful before trying to use `dt` as a date object? – ErikE Aug 05 '14 at 10:26
  • Good point. I will include this in my post, but I think OP needs to tell us what would be the default to be written. An error message possibly? – shree.pat18 Aug 05 '14 at 10:28
5

Your date formatting strings are wrong in couple of places. Try something like this:

string Input = "june 2014";
DateTime dt;
DateTime.TryParseExact(Input.ToString(), "MMMM yyyy",
                       CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
Console.WriteLine(dt.ToString("yyyy-MM"));
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
SoftwareFactor
  • 8,430
  • 3
  • 30
  • 34
  • 2
    You're not going to check if the `TryParse` was successful before trying to use `dt` as a date object? – ErikE Aug 05 '14 at 10:26
  • 1
    ErikE, I just took OP's example and fixed formatting strings. But you are right, checking would be recommended in case input quality is not guaranteed. – SoftwareFactor Aug 05 '14 at 10:29