views:

317

answers:

6

When trying to use the Parse method on the DateTime class I get an exception thrown:

String was not recognized as a valid DateTime.

  • The string reads as "26/10/2009 8:47:39 AM" when outputted.
  • This string is obtained from a group on a match from a regex.
  • None of the strings obtained from this match group will parse to datetime. (WTF?)

Examples of other strings:

26/10/2009 8:47:39 AM
26/10/2009 8:00:41 AM
26/10/2009 7:48:35 AM

The weird thing is, I am sure it has worked before >__<

+2  A: 

Has the culure changed on the machine? 26/10/2009 is a good UK date but a bad US date (for instance)

Pharabus
That had actually just occurred to me.Datetime.parse seems to have an overload for the cultural time format. Just trying to find out how to use it now :)Thanks for you help.
Matthew
+5  A: 

Parse takes regional settings (culture of current thread) into account. Therefore, I'd use ParseExact and specify the correct format explicitly with an invariant culture (or the culture you need, eg. en-US, for AM/PM).

Lucero
+2  A: 

Either call DateTime.Parse() with the culture as a parameter or call DateTime.ParseExact() with the date, the exact format of the date to parse, and the culture:

DateTime.ParseExact()

Justin Niessner
+6  A: 

Parsing strings into DateTime object is almost always a pain. If you know for certain that they will always have the format as your examples do, this should work:

string input = "26/10/2009 8:00:41 AM";
DateTime dateTime = DateTime.ParseExact(input, "dd/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
Fredrik Mörk
I was writing this exact same answer.
Vinko Vrsalovic
Although I was going to add some information about the regional settings (globalization) that affect date parsing.
Vinko Vrsalovic
@Vinko: so did I. It's the pain part. ;) No, seriously, it is a rather complex area that is a common problem source. I did write a sort of lengty answer on the topic a while ago here: http://stackoverflow.com/questions/1437454/date-format-problem
Fredrik Mörk
A: 

You're probably using the wrong culture. The month cannot be 26, so it's not a US timestamp. This works though:

using System;
using System.Globalization;

class Program
{
    static void Main(string[] args)
    {
        DateTime dateTime = DateTime.Parse("26/10/2009 8:47:39 AM",
            CultureInfo.GetCultureInfo("en-GB"));
    }
}
Mark Byers
+1  A: 

I second @Lucero, Parse uses current thread's culture info etc. See also the opposite direction: a ToString question in this context.

Ron Klein