10

I am trying to convert a string to a datetime

I have been using

DateTime convertedDate = DateTime.Parse(lastModificationDate);

to convert the date

my problem is, sometimes the date will be in UK format and sometimes in US format

ie UK 11/09/2011 10:34 US 2/28/2010 13:56

How can I handle both formats when I am not sure which format the string will be in, ie us or uk?

Kate Gregory
  • 18,808
  • 8
  • 56
  • 85
level_zebra
  • 1,503
  • 6
  • 25
  • 44
  • That is impossible without some indication of whether it is US or UK, as you could have 2 identical strings with different meanings. Is there no UTC version of your date available? – Justin Harvey Nov 06 '12 at 16:43
  • 1
    @JustinHarvey: What do you mean by "UTC version"? UTC isn't a format. Both of those values can be in UTC, in different formats. – Jon Skeet Nov 06 '12 at 16:46

2 Answers2

17

You fundamentally can't. You don't have enough data. As a human, which date is involved here?

11/09/2011 10:34

Is that 11th of September or 9th of November?

If you can't tell the difference as a human, there's no chance of a computer doing so.

Now if you can get a signal from elsewhere in the same data source, then that's a start - for example, you could heuristically try to parse all the dates as US format, and all the dates as UK format, and if 100% pass as UK format but 60% fail in the US format (due to trying to days being parsed as invalid months) then you could reasonably assume they're UK dates.

That's never going to be a complete solution though - because you could have one data source with a bunch of dates which are all valid (but with different meanings) in both formats.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

You should be storing your date times in the database in a standardised format, usually UTC, for this very reason.

Then you can parse to the users local date time from UTC using javascript etc.

John Mc
  • 2,862
  • 1
  • 22
  • 37
  • UTC isn't a format, it's a time zone (effectively). Also, there's no indication that there's a database installed here at all. If the value *is* being stored in a database, it shouldn't be stored in a string format at all. – Jon Skeet Nov 06 '12 at 16:46