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

4

8

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?

Taeniasis answered 22/11, 2012 at 13:39 Comment(3)
If I understand the question, then no way. Because you can't treat exactly what date is "2012-11-12", 11th December or 12th November.Gabon
Since it's a string, it has no embedded information about what it is. So, even the fact that this string consists date time is your prior knowledge. So, with no prior knowledge the only option for you is to try to guess the format. But it wont work flawlessly. I believe 1st January is represented equally in "dd-MM-yyyy" and "MM-dd-yyyy". So no, there are no robust techniquesPterodactyl
Does your application generate the date? If yes, you can get it`s culture and from it get exact datetime format. If you get date from external source already as string, you may need to query that source for it's local culture (usually datetime data is stored in one locale) or at least to try datetime.TryParse()Keelung
I
10

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);
        }
Interceptor answered 12/2, 2014 at 19:34 Comment(0)
F
5

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))
Fiscal answered 22/11, 2012 at 13:51 Comment(0)
C
2

If you want to recognize the format, there is almost no way to do this with 100% certainty. However, you may want to go through all the formats supported by given CultureInfo and TryParse them. Unfortunately, this might yield incorrect results, as there is no way of telling the what is a year, month and day in something like this:

10/11/12

Depending on your cultural bias, you may interpret it as October 11, 2012; November 10, 2012 or November 12, 2010.

You haven't mentioned what you want to do with the date, so I will give you just regular best practices:

  1. If you want to transfer dates between different modules of an application, use invariant date format.
  2. If you need to format the date and time, please use default date format for given culture.
  3. Talking about default date format, if you want to accept date entered by end user, you may want to parse free-form input in the culture's default format or you may create (or use preexisting) date-time picker controls. The latter method is preferred.

Ad 1. To convert to invariant date & time format use:

DateTime now = DateTime.UtcNow;
string formatted = now.ToUniversalTime.ToString(CultureInfo.InvariantCulture);

or (to convert to ISO8601-like format):

string formatted = now.ToString("u");

Like-wise, you can parse DateTime from invariant format:

DateTime result;
string source = "11/20/2012 11:22:33";
if (DateTime.TryParse(source, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out result))
{
  // do something with result
}

or (universal format requires no CultureInfo):

DateTime result;
string source = "2012-11-20 11:22:33Z";
if (DateTime.TryParse(source, out result))
{
  // do something
}

Ad 2 & 3. Formatting and parsing for specific culture is similar to formatting and parsing invariant dates, but you need to replace InvariantCulture with a detected, specific instance, say CultureInfo.CurrentCulture.

Depending on the type of your application, you may want to use dedicated Calendar control, i.e. jQuery UI Datepicker.

Culley answered 22/11, 2012 at 18:9 Comment(0)
I
-1

Use the below code :

string sysFormat = CultureInfo.CurrentCulture.DateTimeFormat;

Insensibility answered 22/11, 2012 at 13:50 Comment(1)
Thanks but it gives the current system datetime format but not of that string. :PTaeniasis

© 2022 - 2024 — McMap. All rights reserved.