Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect format Date

Tags:

c#

datetime

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,

like image 200
Kris-I Avatar asked Dec 05 '25 15:12

Kris-I


2 Answers

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.

like image 199
Jon Skeet Avatar answered Dec 07 '25 03:12

Jon Skeet


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
}
like image 40
Darin Dimitrov Avatar answered Dec 07 '25 04:12

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!