'How to validate DateTime format?

I am suppose to let the user enter a DateTime format, but I need to validate it to check if it is acceptable. The user might enter "yyyy-MM-dd" and it would be fine, but they can also enter "MM/yyyyMM/ddd" or any other combination. Is there a way to validate this?



Solution 1:[1]

Are you looking for something like this?

DateTime expectedDate;
if (!DateTime.TryParse("07/27/2012", out expectedDate))
{
    Console.Write("Luke I am not your datetime.... NOOO!!!!!!!!!!!!!!");
}

If your user knows the exact format(s) needed...

string[] formats = { "MM/dd/yyyy", "M/d/yyyy", "M/dd/yyyy", "MM/d/yyyy" };
DateTime expectedDate;
if (!DateTime.TryParseExact("07/27/2012", formats, new CultureInfo("en-US"), 
                            DateTimeStyles.None, out expectedDate))
{
    Console.Write("Thank you Mario, but the DateTime is in another format.");
}

Solution 2:[2]

I assume you want to know if the specified format string is valid...

For this you could round-trip it:

private bool IsValidDateFormat(string dateFormat)
{
    try
    {
        String dts=DateTime.Now.ToString(dateFormat, CultureInfo.InvariantCulture);
        DateTime.ParseExact(dts, dateFormat, CultureInfo.InvariantCulture);
        return true;
    }
    catch (Exception)
    {
        return false;
    }
}

Solution 3:[3]

Unless I am remembering incorrectly, the only invalid DateTime format strings are one character long. You can assume any 2 or more character DateTime format string is valid.

DateTime.ParseExact("qq", "qq", null) == DateTime.Today
DateTime.ParseExact("myy", "501", null) == "05/01/2001"

Standard (1 character)
Custom (>1 character)

For reference, allowed single character strings as formats:

d,D,f,F,g,G,m,M,o,O,r,R,s,T,u,U,y,Y

Any other character, such as q, by itself is invalid. All other strings will be successfully parsed as formatting strings.

Solution 4:[4]

You don't talk about your validation strategy. Anyway you should use something involving regular expressions and than apply allowed patterns. This would help against the formal validity .. then you have to take care about the actual contents and be sure the values are correct according as month, day and year.

Anyway several people suggested to use the DateTime.TryParse() method to let the substrate take care for you. But you'll have to specify the format anyway! so there's no magic! you would fall in ambiguity otherwise

Solution 5:[5]

This works for me-

try
{
  String formattedDate = DateTime.Now.ToString(dateFormat);
  DateTime.Parse(formattedDate);
  return true;
}
catch (Exception)
{
  return false;
}

Solution 6:[6]

static private bool IsValidDateFormat(string dateFormat)
{
  try
  {
    DateTime pastDate = DateTime.Now.Date.Subtract(new TimeSpan(10, 0, 0, 0, 0));
    string pastDateString = pastDate.ToString(dateFormat, CultureInfo.InvariantCulture);
    DateTime parsedDate = DateTime.ParseExact(pastDateString, dateFormat, CultureInfo.InvariantCulture);
    if (parsedDate.Date.CompareTo(pastDate.Date) ==0)
    {
      return true;
    }
    return false;
  }
  catch
  {
    return false;
  }
}

I do use this code - it is a modification of shapiro yaacov posting. It looks as "DateTime.ParseExact" does not throw an exception when using an invalid dateformat string - it just returns "DateTime.Now". My approach is to convert a date in the past to string and then check if this is returned by ParseExact()

Solution 7:[7]

The answer by ZipXap accepts any format that doesn't throw an exception, yet something like "aaaa" will pass that validation and give the current date at midnight ("26-Apr-22 00:00:00" when writing this).

A better aproach is to use the DateTimeStyles.NoCurrentDateDefault option and compare the result to default:

using System.Globalization;

var format = "aaaaa";
try {
    var dt = DateTime.ParseExact(
        DateTime.Now.ToString(format, CultureInfo.InvariantCulture),
        format,
        CultureInfo.InvariantCulture,
        DateTimeStyles.NoCurrentDateDefault);
    return dt != default;
} catch {
    return false;
}
/*
"aaaaa" -> false
"h" -> false
"hh" -> true
"fff" -> true
"gg" -> false
"yyyy gg" -> true
"'timezone: 'K" -> false
"zzz" -> false
*/

Solution 8:[8]

My solution was to mark the input-field as read-only and allow users to change the value only by jqueryui datepicker.

It is intuitive. You can specify your preferred format and need only to validate this one format.

Otherwise you may get really in trouble. What are you going to do with "02/03/2020" in USA you interpret it as the third of February, but for south america it is definitely the second of March. And there are a lot of other Date formats around the globe.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 shapiro yaacov
Solution 3
Solution 4 Diego De Vita
Solution 5 Akash Singh
Solution 6 Leuze
Solution 7
Solution 8