23

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...

Kevin
  • 4,798
  • 19
  • 73
  • 120

8 Answers8

59

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

Lucio M. Tato
  • 5,639
  • 2
  • 31
  • 30
jle
  • 9,316
  • 5
  • 48
  • 67
  • Yes, that looks easy enough. I was thinking I'd have to have separate variables with the converted date values in them, but the way you've shown lets me get around having those extra variables. Thank you! – Kevin Apr 26 '10 at 11:22
  • 1
    @Kevin, just be careful of your culture settings - if you're converting an American date time using a different culture (by default or by accident) you may end up with unexpected results :) – RYFN Apr 26 '10 at 11:42
  • Thanks for the heads-up, Zeus. The program is just a small batch program that will be running every so often on our server. It will basically read a database table, compare two string fields (the fields contain dates like those in my question), and update another field on the same record depending on the comparison. The program will never be running anywhere outside of the country or on a server with culture settings not set to "American". – Kevin Apr 26 '10 at 11:46
  • 1
    Additionally, if ever in other events, when doing dataType.Parse() of a value, if its not in an expected format, it will throw an error exception, you'll need to trap for it.. Just FYI – DRapp Apr 26 '10 at 11:53
16

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!
}
Dan Tao
  • 125,917
  • 54
  • 300
  • 447
6

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.

Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
2

Generally it is a bad idea to compare date as strings.

But if your strings are in the same format (e.g. yyyy/mm/dd means years, then monthes then days) then the comparison may be valid.

Oleks
  • 31,955
  • 11
  • 77
  • 132
2

It could be done with string manipulation, but it would come down to effectively comparing three sets of integers, which as strings would induce more overhead than converting to datetimes. Why would you want to do that?

tsilb
  • 7,977
  • 13
  • 71
  • 98
1

It's preferred to have the date formatted before doing the comparison. Depending in your cultureinfo, the safest way to compare dates is to format the date string to "yyyy-mm-dd".

DateTime d1, d2;
string date1 = "04/26/10";
string date2 = "04/25/10";
d1 = DateTime.Parse(date1.ToString("yyyy-MM-dd"));
d2 = DateTime.Parse(date2.ToString("yyyy-MM-dd"));
if (d1 > d2)
{
      //do something
}
A Ghazal
  • 2,693
  • 1
  • 19
  • 12
1

No. Let the .net framework sort that out for you. It will correctly identify the user date settings and format (using system settings, current thread) and determine which is the month, year and day - especially if that data comes from eg a sql server.

James Westgate
  • 11,306
  • 8
  • 61
  • 68
1

Best practice is to avoid comparing date as string types and compare with the official DateTime object of C#.

If your use-case requires the comparison using string objects then:

  • 1st, make sure the date string format is yyyymmdd as recommend by Lasse V. Karlsen.
  • 2nd, use the string method CompareTo to compare between the dates.

Here's how the method works in your case (Used C# Online Compiler to test this):

using System;
public class Program
{
    public static void Main()
    {
        string fmt = "yyyymmdd";
        string min = "20201206";
        string max = "20210810";
        Console.WriteLine(max.CompareTo(min)); // Output :  1
        Console.WriteLine(min.CompareTo(max)); // Output : -1
        string same1 = "20001212";
        string same2 = "20001212";
        Console.WriteLine(same1.CompareTo(same2)); // Output : 0
        Console.WriteLine(same2.CompareTo(same1)); // Output : 0
        // Summary:
        // 1 = Greater than string param
        // -1 = lesser than string param
        // 0 = equals to string param
    }
}
benhorgen
  • 1,928
  • 1
  • 33
  • 38
OZ_CM
  • 61
  • 1
  • 6