Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String to DateTime in C# UK and US format

Tags:

c#

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?

like image 765
level_zebra Avatar asked Nov 06 '12 16:11

level_zebra


People also ask

How do I convert a string to a date in C #?

You can use the methods like Convert. ToDateTime(String), DateTime. Parse() and DateTime. ParseExact() methods for converting a string-based date to a System.

What is Strptime in C?

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.

What is ParseExact C#?

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.

How do I fix string is not recognized as a valid DateTime?

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.


1 Answers

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.

like image 177
Jon Skeet Avatar answered Oct 18 '22 00:10

Jon Skeet