Created
November 24, 2011 01:50
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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