I am making an application. The application uses date format such as
"2012-11-21 15:22:35"
.
I already know that the format is "yyyy-MM-dd HH:mm:ss"
. But how can I find programmatically the date & time format of an arbitrary input string? Is there any way to do this?
This might help you.. (in the array, add more formats to check)
string[] formats = {"M/d/yyyy", "MM/dd/yyyy",
"d/M/yyyy", "dd/MM/yyyy",
"yyyy/M/d", "yyyy/MM/dd",
"M-d-yyyy", "MM-dd-yyyy",
"d-M-yyyy", "dd-MM-yyyy",
"yyyy-M-d", "yyyy-MM-dd",
"M.d.yyyy", "MM.dd.yyyy",
"d.M.yyyy", "dd.MM.yyyy",
"yyyy.M.d", "yyyy.MM.dd",
"M,d,yyyy", "MM,dd,yyyy",
"d,M,yyyy", "dd,MM,yyyy",
"yyyy,M,d", "yyyy,MM,dd",
"M d yyyy", "MM dd yyyy",
"d M yyyy", "dd MM yyyy",
"yyyy M d", "yyyy MM dd"
};
DateTime dateValue;
foreach (string dateStringFormat in formats)
{
if (DateTime.TryParseExact(strDateTime, dateStringFormat,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dateValue))
//Console.WriteLine("Converted '{0}' to {1}.", dateStringFormat, dateValue.ToString("yyyy-MM-dd"));
Console.WriteLine( dateStringFormat);
}
I think you would run into problems with date strings where the month value is <= 12 as this means that the format of that string could be "yyyy-MM-dd"
or "yyyy-dd-MM"
There is no way of knowing which one is the correct one unless you put a preference in your parser.
For example:
2012/08/07
- "could this be July or August?"
You could just brute-force it and hope there is a CultureInfo matching the format
var datestring = "2012-10-05 12:00:03";
DateTime time;
var matchingCulture = CultureInfo.GetCultures(CultureTypes.AllCultures).FirstOrDefault(ci => DateTime.TryParse(datestring, ci, DateTimeStyles.None, out time))
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