Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

I have two fields:

string date1 = "04/26/10";
string date2 = "04/25/10";

How can I compare these two fields like so?:

if (date2 <= date1)
{
  // perform some code here
}

Can this be done without first converting the fields to a separate date-type variable?

EDIT: I should mention that these values are coming from a database table where the date values are in a string format to begin with. Old legacy code...

like image 965
Kevin Avatar asked Apr 26 '10 11:04

Kevin


People also ask

Can you compare two date strings?

To compare two date strings:Pass the strings to the Date() constructor to create 2 Date objects. Compare the output from calling the getTime() method on the dates.

How do you compare date values?

In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.

How do you compare two date functions?

In JavaScript, we can compare two dates by converting them into numeric values to correspond to their time. First, we can convert the Date into a numeric value by using the getTime() function. By converting the given dates into numeric values we can directly compare them.


3 Answers

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

like image 141
jle Avatar answered Oct 20 '22 17:10

jle


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!
}
like image 16
Dan Tao Avatar answered Oct 20 '22 16:10

Dan Tao


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.

like image 5
Lasse V. Karlsen Avatar answered Oct 20 '22 16:10

Lasse V. Karlsen