简体   繁体   中英

Convert String to DateTime in C# UK and US format

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM