3

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.

Alan Schapira
  • 1,053
  • 4
  • 17
  • 32

1 Answers1

5

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);
Gilles
  • 5,269
  • 4
  • 34
  • 66