I have searched stackoverflow for an answer but no luck. I am developing a windows application and I have some strings in different date formats, eg.
dd/MM/y
To run this program on different culture, i think you should creat a function to indentify the culture of this string format and then use Datetime.Parse
Use DateTime.ParseExact with the different patterns as formats.
If after parsing you really need to use a string representation, use the ToString
method of the DateTime
with the explicit format that you're interested in (so that it is culture-invariant). It's better however to keep the DateTime
because this is format-agnostic.
You could distinguish between those formats that use different separators (i.e. "/" vs "-"). But how would you know if date such as 10/11/2010 represents 10th of November or 11th of October? If one number is not bigger than 12, there is no reliable way to do this without knowing an exact format.
As others have pointed out, if you do know the exact format, then you can use DateTime.ParseExact
.
If you are processing some import file with a lot of dates in the same unknown format, you could try different formats and hope there is exactly one that doesn't give format errors.
Or to put it another way: split the "dates" into three numbers and check the range of values for each of those numbers. Values > 1900 will be years. If you find values from 1 to 31, those will be days. Values from 1 to 12 might be months, but could also be days. Try and identify each of the parts.
The best way is to ask the supplier of those dates for the format.