Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert string in unknown format to date in c#

Tags:

c#

.net

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.

like image 436
Matt Avatar asked Jul 10 '12 07:07

Matt


Video Answer


2 Answers

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.

like image 108
Lucero Avatar answered Sep 24 '22 06:09

Lucero


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.

like image 30
Nikola Anusev Avatar answered Sep 24 '22 06:09

Nikola Anusev