Wednesday, April 29, 2015

.NET C# TimeSpan Comparison Tip

If you ever find yourself in  need of comparing hour, minutes and seconds in a database table stored as integers to say the hour and minute of the day, you can do something like this very simple.

       static void Main(string[] args)
       {
            bool timeOfTheDayEqual= false;
            int hours = 8;
            int minutes = 52;

            TimeSpan scheduledStartTime = new TimeSpan(hours, minutes, 0);
            TimeSpan timeNow = new TimeSpan(DateTime.Now.Hour, DateTime.Now.Minute, 0);

            if (timeNow == scheduledStartTime)
            {
                timeOfTheDayEqual =  true;
            }

            Console.Write(timeOfTheDayEqual);
            Console.ReadKey();
      }


This comparison of the TimeSpan values will always be accurate.

No comments:

Post a Comment