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:
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
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With