Wednesday, August 10, 2011

How to compare Time in C#?

Posted by Rahul Kharde at 4:29 AM

Hi Friends,

I want to compare the system time with 11.00 AM on a button click event. And if the current time is greater than or equal to 11.00 AM, i've to perform some functions.

Compares two instances of DateTime and returns an integer that indicates whether the first instance is earlier than, the same as, or later than the second instance.

C# Code

private void button1_Click(object sender, EventArgs e)

DateTime systemDate = DateTime.Now;
DateTime compareDate = Convert.ToDateTime("11:00AM");
// less than
if (compareDate < systemDate)
    Console.WriteLine("It's past 11 AM");

// equal to
if (compareDate == systemDate)
    Console.WriteLine("It's the same time as");

// greater than
if (compareDate > systemDate)
    Console.WriteLine("It's not 11 AM yet");

If you enjoyed this post and wish to be informed whenever a new post is published, then make sure you subscribe to my regular Email Updates. Subscribe Now!

Kindly Bookmark and Share it:



Have any question? Feel Free To Post Below:


Popular Posts

Recent Comments

© 2011. All Rights Reserved | Help to understand .Net | Template by Blogger Widgets

Home | About | Top