Tonny FuseinOur 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.

 

3 Responses to “How to convert server time to local time using .NET”

  1. ErSehmi says:

    I have a doubt regarding the following code whether it will return the server timezone, instead it will return all the system timezones. Since you are enumerating on all the system timezones.

    // Original Code
    foreach (TimeZoneInfo zoneID in TimeZoneInfo.GetSystemTimeZones())
    {
    Response.Write(zoneID.Id + “”);
    }

    // Modified Code
    // Get the local time zone of server
    TimeZone localZone = TimeZone.CurrentTimeZone;
    string TimeZoneName = localZone.StandardName;

  2. Tonny Fusein says:

    Thanks. Yes, the looping purpose is not to return the server’s timezone (which is Pacific Standard Time) but rather time zone string list, since the method to localize the server time is using that as parameter (string)

    “Mountain Standard Time” is the parameter string so is “Central Standard Time” or “Eastern Standard Time”. These can be obtained by looping instantiate and looping TimeZoneInfo as shown on the article above.

  3. Derek Noonan says:

    My standard practice for this “issue” is to use DateTime.UtcNow for all of these kinds of scenarios. Then when you need to _display_ these dates then do the conversion

Leave a Reply

iBlog by PageLines