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/yyyy
MM/dd/yyyy
MM-dd-yyyy
dd-MM-yyyy
dd/MM/yyyy hh:mm::ss
MM/dd/yyyy hh:mm::ss
etc...
But I need to convert in to a common format - dd/MM/yyyy
. The application can run in any windows machines in different culture.
What is the correct way to do it?
EDIT: One more thing I may not know what the format of incoming string.
Thanks in advance.
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 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