Handling Time Zones in a Web Application
One aspect of developing a web application that will be used across a large geographical area is handling dates and times such that they display correctly for users in different time zones. In an application we are currently working on, we adapted the following principles to help with this objective:
- The user’s time zone would be part of the user’s profile data.
- DateTimes would be stored in UTC in the database.
- DateTimes in the data layer would always be UTC.
- DateTimes in the UI layer should always be in the user’s time zone.
A design decision that we made was to store a small set of data about the user on the session. The user’s time zone was part of this data. Below are some methods that were implemented to help follow the above principles:
public static DateTime ToUserTime(this DateTime date, string timeZone)
{
var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(timeZone);
return TimeZoneInfo.ConvertTimeFromUtc(date, timeZoneInfo);
}
public static DateTime ToUniversalTime(this DateTime date, string timeZone)
{
var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(timeZone);
return TimeZoneInfo.ConvertTimeToUtc(date, timeZoneInfo);
}
public static DateTime GetDatabaseTime()
{
return DateTime.UtcNow;
}
public static DateTime GetUserTime(string timeZone)
{
return DateTime.UtcNow.ToUserTime(timeZone);
}
public static string GetTimeZone()
{
if (HttpContext.Current != null && HttpContext.Current.Session != null)
{
var timeZone = HttpContext.Current.Session[“TimeZone”]; if (timeZone != null)
{
return timeZone.ToString();
}
using (var model = new Entities())
{
var user = model.Users.FirstOrDefault(u => u.UserName == HttpContext.Current.User.Identity.Name); if (user != null)
{
SetTimeZone(user.TimeZone);
return user.TimeZone;
}
}
}
return null;
}
public static void SetTimeZone(string timeZone)
{
if (HttpContext.Current != null && HttpContext.Current.Session != null)
{
HttpContext.Current.Session[“TimeZone”] = timeZone;
}
}
public static DateTime ConvertToUserTime(this DateTime date)
{
var timeZone = MembershipHelper.GetTimeZone();
return date.ToUserTime(timeZone);
}
public static DateTime ConvertToUniversalTime(this DateTime date)
{
var timeZone = MembershipHelper.GetTimeZone();
return date.ToUniversalTime(timeZone);
}
Leave a Reply
Your email is safe with us.