C# DateTime.TryParseExact with optional parameters

Viewed 917

The code below works fine, just wondering if there's a more elegant way of achieving the same thing? The dates below should be valid, anything other than that should not:

  • 1/12/2017
  • 1/12/2017 11:10
  • 1/12/2017 11:10:30
  • 15/5/2017
  • 15/5/2017 11:10
  • 15/5/2017 11:10:30
  • 1/5/2017
  • 1/5/2017 11:10
  • 1/5/2017 11:10:30
  • 25/12/2017
  • 25/12/2017 11:10
  • 25/12/2017 11:10:30

In other words: it should work with 1 and 2 digits days/months, and it should work with and without time, including or not seconds.

var validDateTimeFormats = new[]
{
   "d/MM/yyyy",
   "d/MM/yyyy HH:mm",
   "d/MM/yyyy HH:mm:ss",
   "dd/M/yyyy",
   "dd/M/yyyy HH:mm",
   "dd/M/yyyy HH:mm:ss",
   "d/M/yyyy",
   "d/M/yyyy HH:mm",
   "d/M/yyyy HH:mm:ss",
   "dd/MM/yyyy",
   "dd/MM/yyyy HH:mm",
   "dd/MM/yyyy HH:mm:ss"
};

DateTime dateTime;
if (DateTime.TryParseExact(dateTimeStr, validDateTimeFormats,
CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
{
   // My logic
}
1 Answers

Thanks @Steve for the suggestion. dd and MM combinations are not needed.

Final code:

var validDateTimeFormats = new[]
{
   "d/M/yyyy",
   "d/M/yyyy HH:mm",
   "d/M/yyyy HH:mm:ss"
};

DateTime dateTime;
if (DateTime.TryParseExact(dateTimeStr, validDateTimeFormats,
CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
{
   // My logic
}
Related