Skip to content

Instantly share code, notes, and snippets.

@gkinsman
Created November 24, 2011 01:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gkinsman/1390459 to your computer and use it in GitHub Desktop.
Save gkinsman/1390459 to your computer and use it in GitHub Desktop.
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();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment