Hi,
Is there a way, a good way, to test if a string than I want to transform in DateTime
is dd/MM/yyyy
or MM/dd/yyyy
?
Thanks,
Hi,
Is there a way, a good way, to test if a string than I want to transform in DateTime
is dd/MM/yyyy
or MM/dd/yyyy
?
Thanks,
No, but you could try both when parsing:
DateTime result;
if (DateTime.TryParseExact(
"05/10/2010",
new[] { "MM/dd/yyyy", "dd/MM/yyyy" },
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out result)
)
{
// successfully parsed date => use the result variable
}
No, because it could be both. Is 11/10/2010 November 10th or October 11th?
Yes, in some cases (if one number is above 12) it will be unambiguous - but I think it's better to force one format or the other. If you just treat anything which can be done as MM/dd/yyyy that way, and move on to dd/MM/yyyy if it fails (or the other way round) then you'll get some very surprised users.
If this is part of a web application or something similar, I would try to make it completely unambiguous by using month names instead of numbers where possible.
Take a look at DateTime.ParseExact and DateTime.TryParseExact.
string date1 = "24/12/2010";
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime dt1 = new DateTime(1, 1, 1);
bool dt1Valid = false;
try
{
dt1 = DateTime.ParseExact(date1, "dd/MM/yyyy", provider);
dt1Valid = true;
}
catch
{
dt1Valid = false;
}
This problem will exist until all accepts and uses the ISO way. I'm a Swedish programmer working a lot with American and English clients and it's surprisingly hard to get these clients to use the standardized date format.
ISO 8601 - Use it!