Just a little bit about the background

Recently I am working on a data dictionary project. What is data dictionary? Refer to wiki definition http://en.wikipedia.org/wiki/Data_dictionary

We decided to choose ASP.NET MVC 2 as our server technology and use YUI 2 to facilitate our UI work.

Why not JQuery but YUI?

I just love it. Less time more done that is YUI 2 gives us. It provides abundant UI widgets to create RIA application. Examples and documents are complete.

After we finished first sprint and present our work for the first demo.

During the demo someone asked,

As we all know ASP.NET is a server technology and it should not know about the client time zone. How did you guys implement it without asking user to provide the time zone information?

The magic is only one line of JavaScript.

 

Solution

Here is the code to store the time zone information into cookie. I just use YAHOO cookie component to do so. But it should be easy for other JavaScript frameworks to do this or you can just do this manually.

 

YAHOO.util.Cookie.set("TimeZoneOffset", new Date().getTimezoneOffset(), { path: "/" });

Note: The result of getTimezoneOffset method is a bit tricky. For example, if your time zone is GMT+8, -480 will be returned.

 

That's all what I need to do with UI side. How about the code in ASP.NET?

As I mentioned we choose ASP.NET MVC 2, so I just wrote a function to extend HtmlHelper class like this,

 

public static string DisplayDateTime(this HtmlHelper helper, DateTime dateTime)
{
    int timeZoneOffset;

    var value = HttpContext.Current.Request.Cookies["TimeZoneOffset"].Value;

    if (int.TryParse(value, out timeZoneOffset))
    {
        dateTime = dateTime.AddMinutes(-timeZoneOffset);
    }

    return dateTime.ToString("M/d/yyyy h:mm tt");
}

And then, you can use it like other HtmlHelper methods in your views.

 

<%: Html.DisplayDateTime(item.CreatedDT) %>

Simple, isn't it?

This solution is not only limited to ASP.NET. You can write your own logic in other server technology like JEE, Rails, Python…

 

Reference:

http://www.windowsitpro.com/article/aspnet2/it-s-about-time.aspx

http://stackoverflow.com/questions/832986/how-to-work-with-timezone-in-asp-net/833377#833377

 posted on 2010-08-17 12:55  助平君  阅读(523)  评论(0编辑  收藏  举报