Is there a way to compare date "strings" in C# without converting the strings?

No, but it is not difficult to convert to a date in C#.

if ( DateTime.Parse(date2,CultureInfo.InvariantCulture) <=  DateTime.Parse(date1,CultureInfo.InvariantCulture))

{
  // perform some code here
}

CultureInfo depends on the format the string dates have in the legacy DB. See: DateTime formats used in InvariantCulture


If your dates are actually stored as strings in the database, it seems like you can't be sure they'll be in a valid format before parsing. For that reason I'd suggest a small variation on jle's answer:

DateTime d1, d2;
if (DateTime.TryParse(date1, out d1) &&
    DateTime.TryParse(date2, out d2) &&
    d2 <= d1)
{
    // perform some code here
}
else
{
    // strings didn't parse, but hey,
    //at least you didn't throw an exception!
}

At the very least you need to pick apart the strings in order to compare them in the right order.

If you want to leave them as strings, then you need to reorder them with LARGEST->SMALLEST units, so this:

yyyy/mm/dd

can be compared directly, but not the format you have. With your format, you need to split it, and either recombine it like above, or compare the individual pieces in the right order.

Having said that, it is rather easy to convert the strings to DateTime using DateTime.ParseExact.

Tags:

C#