Liaqat Shaikh
Liaqat Shaikh

Reputation: 19

How to compare strings representing DateTime?

I have two strings which contains datetime i want to check if first string datetime less then second , how to do if have already try string.compare which not works for me

Upvotes: 0

Views: 1237

Answers (2)

Shubham
Shubham

Reputation: 351

int result = date1.CompareTo(date2);

in which date1 and date2 must be datetime variables

Upvotes: 0

rtshmittl
rtshmittl

Reputation: 64

The problem can be divided into 2 parts

  1. Parsing the datetime value from string to datetime
  2. Comparing the two datetime values to understand which one is larger.

Parsing: Use the DateTime.Parse() method to parse the datetime

 string dateInput = "Jan 1, 2009";
 DateTime parsedDate = DateTime.Parse(dateInput);
 Console.WriteLine(parsedDate);
 // Displays the following output on a system whose culture is en-US:
 // 1/1/2009 12:00:00 AM

Refer this for DateTime.Parse(). You can also use DateTime.ParseExact() if you know the string pattern confirms to the pattern specified.

Comparing: Use the DateTime.Compare() to compare two datetime values.

Refer this link for Datetime.Compare()

So the actual code would become something like this:

using System;

public class Example
{
   public static void Main()
   {    
    string d1 = "Jan 1, 2009";
    string d2 = "Feb 2, 2008";
    DateTime date1 = DateTime.Parse(d1);
    DateTime date2 = DateTime.Parse(d2);
    int result = DateTime.Compare(date1, date2);
    string relationship;

    if (result < 0)
     relationship = "is earlier than";
    else if (result == 0)
     relationship = "is the same time as";
    else
     relationship = "is later than";

    Console.WriteLine("{0} {1} {2}", date1, relationship, date2);
   }
} 

Upvotes: 1

Related Questions