Amit Kumar Das
Amit Kumar Das

Reputation: 211

Datetime comparison in C#

I have the current UTC datetime as follows:

 public void GetUTCTime()
        {
            var now = DateTime.UtcNow;
            string utc = now.ToString("yyyy-MM-dd HH:mm:ss");
            Console.WriteLine("Current UTC time is: " + utc);
        }

My another date is like,

String myDate = "2017-06-15 16:10:16";

Now i have to find out which datetime is latest.

Upvotes: 0

Views: 260

Answers (1)

user8104581
user8104581

Reputation:

Use DateTime.Compare:

if (DateTime.Compare(time_1, time_2) > 0) // if time_1 is later than time_2
{
    // Your code here
}

According to the linked MSDN documentation:

If the returned value is...

  • Less than zero: time_1 is earlier than time_2
  • Zero: time_1 is the same as time_2
  • Greater than zero: time_1 is later than time_2

Converting the string date back to DateTime:

Since you're using the date as a string, you have to convert it back to DateTime before comparing, like that:

DateTime convertedDate = DateTime.Parse(stringDate);

Upvotes: 1

Related Questions