gkinsman
11/24/2011 - 1:50 AM

A utility class for creating a countdown in various timezones to a time of day.

A utility class for creating a countdown in various timezones to a time of day.

public static class DateTimeUtils {
		public static TimeSpan TimeTill(this DateTime now, TimeSpan target) {


			//TimeOfDay gives you the time elapsed since midnight as a TimeSpan
			var difference = target.Subtract(new TimeSpan(now.Hour,now.Minute,now.Second));

			//check for negative TimeSpan, 
			//it means the target time occurs on the next day, just add 24 hours
			if (difference < TimeSpan.Zero)
				difference = difference.Add(TimeSpan.FromHours(12));

			return difference;
		}

		public static IEnumerable<KeyValuePair<TimeSpan,TimeZoneInfo>> GetTimeZonesCountdown(this TimeSpan target) {

			var queue = new PriorityQueue<TimeSpan, TimeZoneInfo>();
			var timezones = TimeZoneInfo.GetSystemTimeZones();

			var now = DateTime.UtcNow;

			foreach(var tz in timezones) {
				var time = TimeZoneInfo.ConvertTimeFromUtc(now, tz);

				var timeTill = time.TimeTill(target);

				if(timeTill.CompareTo(new TimeSpan(0,0,0)) <= 0) {
					timeTill = time.TimeTill(target.Add(new TimeSpan(12, 0, 0)));
				}

				queue.Enqueue(timeTill, tz);
			}

			while(!queue.IsEmpty) {
				yield return queue.Peek();
				queue.Dequeue();
			}
		}
	}