DiscountASP.NET

How to convert server time to local time using .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 quite often is how to modify 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>

Visit DiscountASP.NET to learn more about our ASP.NET hosting services.

Exit mobile version