3

I am trying to Parse a String date and time into a single .NET DateTime object. I have the following code:

string dtObjFormat = "dd MMM YYYY HH:mm";
string mydatetimemash = e.Date + " " + e.Time; // this becomes 25 May 2013 10:30
DateTime dt;

if (DateTime.TryParseExact(mydatetimemash, dtObjFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
    Console.WriteLine(dt);
} else 
{
    dt = DateTime.Now;
    Console.WriteLine(dt);
}

But the TryParseExact always returns false for me, meaning the Parse fails. What am I doing wrong?

7
  • 5
    I think your Y's need to be lower case. Commented Apr 15, 2013 at 16:50
  • @JMK please post as Answer, so that I mark it as Answer. You were right! :) Commented Apr 15, 2013 at 16:53
  • 2
    @JKM I bet it's just test code; in the real code he will be parsing real dates. Commented Apr 15, 2013 at 17:06
  • I'm printing to the Console for debugging purposes. I have other things that I want to do with the DateTime object ;) Commented Apr 15, 2013 at 17:06
  • Surely @JMK gave the right answer. DateTime.TryParseExact("25 May 2013 10:30", "dd MMM yyyy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt) works fine, whereas the variant with "YYYY" doesn't work. Commented Apr 15, 2013 at 17:12

1 Answer 1

2

Your Y's need to be lower case, like so:

string dtObjFormat = "dd MMM yyyy HH:mm";
string mydatetimemash = e.Date + " " + e.Time; // this becomes 25 May 2013 10:30
DateTime dt;

if (DateTime.TryParseExact(mydatetimemash, dtObjFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
    Console.WriteLine(dt);
} else 
{
    dt = DateTime.Now;
    Console.WriteLine(dt);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Haha finally :D Thank You very much JMK. ^_^

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.