Time Utilities Tutorial

This tutorial aims to teach you about the time utilities that the DigitallyCreated.Utilities.Bcl assembly has. It assumes you are familiar with C#.

TimeSpan to Ago String (eg "2 minutes ago")

Sometimes you want to show a TimeSpan to the user as a relative to now time string (an "ago" string). The ToAgoString() extension method off of TimeSpan is good for that.

new TimeSpan(0,0,30).ToAgoString(); //30 seconds: "just now"
new TimeSpan(0,14,0).ToAgoString(); //14 minutes: "14 minutes ago"
new TimeSpan(1,0,0).ToAgoString(); //14 minutes: "14 minutes ago"
new TimeSpan(1,0,0).ToAgoString(); //1 hour: "1 hour ago"
new TimeSpan(1,0,0,0).ToAgoString(); //1 day: "yesterday"
new TimeSpan(5,0,0,0).ToAgoString(); //5 days: "5 days ago"
new TimeSpan(8,0,0,0).ToAgoString(); //8 days: "1 week ago"
new TimeSpan(70,0,0,0).ToAgoString(); //70 days: "2 months ago"
new TimeSpan(450,0,0,0).ToAgoString(); //450 days: "1 year ago"

Obviously as the time span increases, the textual representation gets more and more inaccurate. However, this is acceptable, as generally using this representation means you don't really care about accuracy anyway.

Converting between Olson Time Zones (TzIds) and Windows system TimeZoneInfos

Sometimes you may need the ability to take a TzId string (eg Australia/Melbourne) and get a TimeZoneInfo for that TzId. Unfortunately, the Windows system timezones are nowhere near as comprehensive as the Olson database, so the converter that DigitallyCreated.Utilities.Bcl has is on a best effort basis. There is an XML mapping file that is embedded into the assembly that contains ~140 mappings. You can add to this XML if you require others and recompile the project yourself.

To use the converter facility, you simply call TimeUtils.GetTimeZoneInfoForTzId(tzId).

TimeZoneInfo tzi = TimeUtils.GetTimeZoneInfoForTzId("Australia/Melbourne");

You can convert back the other way too, even where multiple TzIds cover the one Windows timezone:

//Where tzi is a TimeZoneInfo object
string tzId = tzi.ToTzId();
IEnumerable<string> tzIds = tzi.GetAllTzIds();

Last edited Mar 5, 2010 at 5:52 AM by dchambers, version 1

Comments

No comments yet.