I need to compare a time in a table with the current system time and need to pop up a notification. But how can I compare both? here is my code and DB:
SqlCommand cmd = new SqlCommand("SELECT RestTime FROM FunTime WHERE rest_id=1",conn);
String currenttime = DateTime.Now.ToString("HH:mm:ss tt");
if (cmd == currenttime)
{
//Some code here
}
How can I achieve it using C#? thanks
Suppose you have two times, one is current System and another from database(let's say it's 11:00 AM), then you can compare two times using the code below
Solution 1:
DateTime t1 = DateTime.Now; DateTime t2 = Convert.ToDateTime("11:00:00 AM"); int i = DateTime.Compare(t1,t2); //if t1 is less than t2 then result is Less than zero //if t1 equals t2 then result is Zero //if t1 is greater than t2 then result isGreater zero
In the above example, "11:00:00 AM" can be your database time and Datetime.Now
, current system time
Solution 2:
DateTime t1 = Convert.ToDateTime(DateTime.Now); DateTime t2 = Convert.ToDateTime("11:00 AM"); if (t1.TimeOfDay.Ticks > t2.TimeOfDay.Ticks) { //If Time t1 is greater than time t2, do something here }
Solution 3:
if (System.DateTime.Now.Hour < 9) //here 9 is database Hours { Console.WriteLine("On Time"); // if current time is less then 9, he is ontime } else if (System.DateTime.Now.Hour > 9) { Console.WriteLine("Late"); // if current time is more then 9, he is late } else { if (System.DateTime.Now.Hour == 9) //First check Hours { if (System.DateTime.Now.Minute > 20) //Then Check Minutes { Console.WriteLine("Late"); // if current time is 9 and pass 20 mins, he is late } else { Console.WriteLine("On Time"); // if current time is 9 and less then 20 mins, he is on time } } }
You can use any of the above methods, but please read the comments with code, to help your understand the answer clearly, thanks
You can use TimeSpan also in C#, something like this, suppose you have two times, start time and end time, then you can check it with System time using the code below
TimeSpan start = TimeSpan.Parse("22:00"); // 10 PM TimeSpan end = TimeSpan.Parse("02:00"); // 2 AM TimeSpan now = DateTime.Now.TimeOfDay; if (start <= end) { // start and stop times are in the same day if (now >= start && now <= end) { // current time is between start and stop } } else { // start and stop times are in different days if (now >= start || now <= end) { // current time is between start and stop } }
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly