Using the New DateTime Support in .NET 3.5 via MVC & jQueryPosted in ASP.NET, BlogSvc, C#, MVC, jQuery by Jarrett on 10/9/2008 2:24:00 AM - CST
The DateTimeOffset structure represents a date and time value, together with an offset that indicates how much that value differs from UTC. Thus, the value always unambiguously identifies a single point in time. A DateTimeOffset value is not tied to a particular time zone, but can originate from any of a variety of time zones. The TimeZoneInfo class makes it possible to work with dates and times so that any date and time value unambiguously identifies a single point in time. Taking advantage of time zone support in the .NET Framework is possible only if the time zone to which a date and time value belongs is known when that date and time object is instantiated.
So the MSDN documentation is not clear on which class can make a date/time unambiguous. However, the last sentence is the best clue. We must capture both the UTC value and an originating time zone.
For an ASP.NET MVC application we can add configuration to associate all date/times to our preferred time zone.
With this configuration, we can now write an HtmlHelper extension to display a DateTimeOffset in our preferred time zone.
Call the extension method and pass it either a DateTimeOffset or a DateTime
This will result in the follwing html:
<abbr title='Tuesday, October 07, 2008 10:01 PM (GMT-06:00) Central Time (US & Canada)'>10/7/2008 10:01 PM - CST</abbr>
This gives an abbreviated date/time display at your preferred time zone.
However, you may want to display time relative to the user browsing your website. There are two ways to accomplish this:
- Ask and store each user's time zone
The first option is commonly used with forums and requires the user to register and choose their preferred time zone. The second option makes much more sense for content websites (such as a blog) since it can occur automatically without registration.
There is already a great plugin for jQuery that can display fuzzy times that are directly relative to the user. It is called the Time Ago Plugin. To use it, lets create another helper extension that utilizes a micro-format:
This creates abbreviations in the html, that when activated through jQuery show times that will be automatically updated even after the user has loaded the page.
This DateTime display is much more recognizable and personable to the casual user.
Head on over to the BlogSvc website to download the code.
Update: here is a bonus function that will allow you to format the date (with access to the time zone information) anyway you'd like.
Call it like