I am converting strings to DateTime and have the strings coming in like this:
string dateTimeBeforeDayTen = '2/05/2016';
string dateTimeBeforeAfterTen = '12/05/2016';
Now if I am parsing the dateTimeBeforeAfterTen, I know I can use:
DateTime myDateTime;
DateTime.TryParseExact(dateTimeBeforeAfterTen, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out myDateTime);
But what do I do if I want to parse for either of them. I know I could do:
DateTime myDateTime;
if(!DateTime.TryParseExact(dateTimeBeforeAfterTen, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out myDateTime));
    DateTime.TryParseExact(dateTimeBeforeAfterTen, "d/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out myDateTime);
But is there a better way to do this? I am storing the DateTime format in the DB and would like to keep it as a single string.
A single "d" will work both for one and two number days. So just use "d/MM/yyyy".
Format string
"d"
The day of the month, from 1 through 31.
2009-06-01T13:45:30 -> 1
2009-06-15T13:45:30 -> 15
This works:
string dateTimeBeforeDayTen = "2/05/2016";
string dateTimeBeforeAfterTen = "12/05/2016";
DateTime myDateTime, myDateTime2;
DateTime.TryParseExact(dateTimeBeforeDayTen, "d/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out myDateTime);
DateTime.TryParseExact(dateTimeBeforeAfterTen, "d/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out myDateTime2);
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