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 can use the methods like Convert. ToDateTime(String), DateTime. Parse() and DateTime. ParseExact() methods for converting a string-based date to a System.
The strptime() function converts the character string pointed to by buf to values that are stored in the tm structure pointed to by tm, using the format specified by format. The format contains zero or more directives.
ParseExact(String, String, IFormatProvider) Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.
By parsing the string representation of a date and time value. The Parse, ParseExact, TryParse, and TryParseExact methods all convert a string to its equivalent date and time value. The following example uses the Parse method to parse a string and convert it to a DateTimevalue.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With