Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out the Date time format of string date in c#

I am making an application. The application uses date format such as "2012-11-21 15:22:35".
I already know that the format is "yyyy-MM-dd HH:mm:ss". But how can I find programmatically the date & time format of an arbitrary input string? Is there any way to do this?

like image 397
Dany Avatar asked Nov 22 '12 13:11

Dany


2 Answers

This might help you.. (in the array, add more formats to check)

string[] formats = {"M/d/yyyy", "MM/dd/yyyy",                                    
                            "d/M/yyyy", "dd/MM/yyyy", 
                            "yyyy/M/d", "yyyy/MM/dd",
                            "M-d-yyyy", "MM-dd-yyyy",                                    
                            "d-M-yyyy", "dd-MM-yyyy", 
                            "yyyy-M-d", "yyyy-MM-dd",
                            "M.d.yyyy", "MM.dd.yyyy",                                    
                            "d.M.yyyy", "dd.MM.yyyy", 
                            "yyyy.M.d", "yyyy.MM.dd",
                            "M,d,yyyy", "MM,dd,yyyy",                                    
                            "d,M,yyyy", "dd,MM,yyyy", 
                            "yyyy,M,d", "yyyy,MM,dd",
                            "M d yyyy", "MM dd yyyy",                                    
                            "d M yyyy", "dd MM yyyy", 
                            "yyyy M d", "yyyy MM dd"
                           };

        DateTime dateValue;

        foreach (string dateStringFormat in formats)
        {
            if (DateTime.TryParseExact(strDateTime, dateStringFormat,
                                       CultureInfo.InvariantCulture,
                                       DateTimeStyles.None,
                                       out dateValue))
                //Console.WriteLine("Converted '{0}' to {1}.", dateStringFormat, dateValue.ToString("yyyy-MM-dd"));                
                Console.WriteLine( dateStringFormat);
        }
like image 51
Rohit Avatar answered Sep 28 '22 01:09

Rohit


I think you would run into problems with date strings where the month value is <= 12 as this means that the format of that string could be "yyyy-MM-dd" or "yyyy-dd-MM"

There is no way of knowing which one is the correct one unless you put a preference in your parser.

For example: 2012/08/07 - "could this be July or August?"

You could just brute-force it and hope there is a CultureInfo matching the format

 var datestring = "2012-10-05 12:00:03";
 DateTime time;
 var matchingCulture = CultureInfo.GetCultures(CultureTypes.AllCultures).FirstOrDefault(ci => DateTime.TryParse(datestring, ci, DateTimeStyles.None, out time))
like image 27
Christian Westman Avatar answered Sep 28 '22 02:09

Christian Westman