Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting different time zone in IIS or web.config

Tags:

timezone

c#

iis

I am logging time in many places

If Request.DynamicSettings.AirlineSettings.AirlineGeneralSettings.TimeLogEnabled Then
                        StartTime = DateTime.Now
                        LogTime(Reflection.MethodBase.GetCurrentMethod.DeclaringType.FullName, Reflection.MethodBase.GetCurrentMethod.Name, StartTime, DateTime.Now, "AB-SCR(I)", 0,)
    End If

all places i have used

DateTime.Now

I am facing an issue now, I am currently hosting this in a gulf server, GMT +4:00 I need to host this same project for another country at Gmt +3Gmt for this hosting i need time to be logged using that country's local time.

Is there any way to do this, without having to modify each and every line of my code.

i have seen this article timzone with asp.net but as my service is already up i have a lot of codes to change, i am looking for a simpler solution.

thanks.

like image 211
fizmhd Avatar asked Nov 21 '15 03:11

fizmhd


People also ask

How do I change the time zone on my server?

Using the Windows Start Menu, open Server Manager. Locate Time zone in the local server properties section. Click the current timezone, which is UTC Coordinated Universal Timeby default. In the Date and Time window, click Change time zone.


1 Answers

A few things:

  1. You cannot change the time zone in the IIS configuration or web.config. This is not an IIS problem, but rather a problem in your application code.

  2. DateTime.Now should never be used in a server side application, such as an ASP.Net web application. Read The case against DateTime.Now.

  3. If you are just timing how long something takes to run, don't use DateTime at all. Instead, use System.Diagnostics.Stopwatch.

    Stopwatch sw = Stopwatch.StartNew();
    // ...do some work ...
    sw.Stop();
    TimeSpan elapsed = sw.Elapsed;  // how long it took will be in the Elapsed property
    
  4. If you actually want the current time in a specific time zone, then you need to know the time zone identifier. (GMT+4 and GMT+3 are not time zones, but rather time zone offsets see "Time Zone != Offset" in the timezone tag wiki.) You can see a list of Windows time zones by using TimeZoneInfo.GetSystemTimeZones(), or by calling tzutil /l on the command line.

    Then in your application:

    string tz = "Arabian Standard Time";
    DateTime now = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tz);
    

    You should probably refactor your code such that this is done inside your LogTime method. Then you will have only one place to set the time zone for your application.

like image 109
Matt Johnson-Pint Avatar answered Sep 18 '22 09:09

Matt Johnson-Pint