I would like to be able to get the format string from a DateTime string.
e.g.
"2012-12-08 15:00:00" => "yyyy-MM-dd HH:mm:ss"
"2013/30/01 16:00" => "yyyy/dd/MM HH:mm"
Is this possible?
I would like to be able to get the format string from a DateTime string.
e.g.
"2012-12-08 15:00:00" => "yyyy-MM-dd HH:mm:ss"
"2013/30/01 16:00" => "yyyy/dd/MM HH:mm"
Is this possible?
You can have a set of predefined formats and parse the date and see if it passes, then you can get the string format you are looking for.
Refer to the answer but its in java - How to get the given date string format(pattern) in java?
You can try by writing the below code to get
yyyy/dd/MM HH:mm
format.It would give you same
HH:mm
format.I had the same idea as Jon Skeet and went to implement it:
There is space for improvement here (e.g. the hardcoded
DateTimeStyles.None
doesn't help, an overload which assumes the current culture would also be useful), but you can use it like this:It would be very hard to do this in a completely general way, but one option would be to extract the relevant
DateTimeFormatInfo
that you're interested in (usingCultureInfo.DateTimeFormat
), extract the culture-specific patterns from that (LongDatePattern
,LongTimePattern
etc), combine the patterns appropriately in some cases (e.g.ShortDatePattern
spaceShortTimePattern
) and then try each pattern in turn usingDateTime.TryParseExact
- remembering to still specify the culture each time in order to handle date separators etc appropriately.When
DateTime.TryParseExact
returnstrue
, you know you've got a pattern which will parse the given text.Sample code - including showing an example where you'd expect it to work but it doesn't:
You could potentially hard-code some "extra" date and time formats which you expect to work.
EDIT: To handle ambiguity, you could easily make
GuessPattern
return anIEnumerable<string>
instead of a single string: