In order to calculate the time remaining before a specific time of day, .NET has a nice class called TimeSpan. With TimeSpan you can perform addition or subtraction on DateTime objects.
I ran into a situation where I needed to calculate the time remaining before it was 14:00. If it was 14:00 or greater, then I needed to calculate it for the following day.
The solution was pretty simple:
DateTime now = DateTime.Now; DateTime target = new DateTime( DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 14, 00, 00 ); //Add 1 day to the target time if we're already at 14:00+ today. if ( now.Hour >= 14 ) target = target.AddDays( 1 ); TimeSpan difference = target - now; var timeRemain = difference.ToString( @"hh\:mm\:ss" );
The result is a nice string that looks similar to this:
Hope this helps someone looking for a similar solution!