How to validate DateTime format?

Viewed 52974

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?

9 Answers

This works for me-

try
{
  String formattedDate = DateTime.Now.ToString(dateFormat);
  DateTime.Parse(formattedDate);
  return true;
}
catch (Exception)
{
  return false;
}
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()

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
*/
Related