How to convert server time zone to local timezone using .NET

Programming, error messages and sample code > ASP.NET

Our U.S. data center is located in California, so the web and database servers have their timezone set to Pacific Time.

One of the questions we get all the time is how to change server time so it matches the time zone of the customer or users. Unfortunately, the answer is — you can’t. The web server can only run in one time zone, so the time is going to be “off” in the other 39 time zones.

What you can do to work around this is convert the server time to your local time. .NET makes this easy with a built-in TimeZoneInfo class that can be used to convert one time zone to another.

This sample shows how to convert server time from Pacific Standard Time zone (GMT -7:00) to Mountain Standard Time (GMT -6:00):


<%@ Page Language="C#" AutoEventWireup="true"%>
<script language="C#" runat="server">
  protected DateTime GetCurrentTime()
        {
            DateTime serverTime = DateTime.Now;
            DateTime _localTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(serverTime, TimeZoneInfo.Local.Id, "Mountain Standard Time");
            return _localTime;
        }
 
  protected void Page_Load(object sender, EventArgs e)
        {
        Response.Write(GetCurrentTime());
        }
</script>


And this is how to get the TimeZoneId on the server:

<%@ Page Language="C#" AutoEventWireup="true"%>
<script language="C#" runat="server">
  protected void Page_Load(object sender, EventArgs e)
        {
           foreach (TimeZoneInfo zoneID in TimeZoneInfo.GetSystemTimeZones())
            {
                Response.Write(zoneID.Id + "<br/>");
            }
        }
</script>