Search code examples
c#.net-coretimezonedatetimeoffset

How do I get local time in another timezone in dot net core


I'm working on a problem in which I need to get the current date and time in another timezone. I don't know what timezone my code will be run on, and it needs to work on both windows and linux machines.

I have not found any way of doing this. Any ideas?

(P.S: I specifically need to find what time it is in Sweden including daylight savings from any arbitrary timezone the code might be running in).


Solution

  • The IANA time zone ID for Sweden is "Europe/Stockholm" (for use on Linux, OSX, and other non-Windows platforms). The Windows time zone ID for Sweden is "W. Europe Standard Time".

    Thus, you can do the following:

    // Determine the time zone ID for Sweden
    string timeZoneId = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
        ? "W. Europe Standard Time"
        : "Europe/Stockholm";
    
    // Get a TimeZoneInfo object for that time zone
    TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
    
    // Convert the current UTC time to the time in Sweden
    DateTimeOffset currentTimeInSweden = TimeZoneInfo.ConvertTime(DateTimeOffset.UtcNow, tzi);
    

    If desired, you can simplify this by using my TimeZoneConverter library, which allows you to use either id on any platform.

    TimeZoneInfo tzi = TZConvert.GetTimeZoneInfo("Europe/Stockholm");
    DateTimeOffset currentTimeInSweden = TimeZoneInfo.ConvertTime(DateTimeOffset.UtcNow, tzi);
    

    If running on .NET 6 or newer, and you have ICU globalization support enabled, you no longer need to use my library. .NET will automatically convert from one format to the other if needed. So you can just do:

    TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("Europe/Stockholm");
    DateTimeOffset currentTimeInSweden = TimeZoneInfo.ConvertTime(DateTimeOffset.UtcNow, tzi);
    

    Also note that the time zone where the code is running is not relevant, nor should it be. The daylight savings rules of Sweden are the only that are relevant, not those of the time zone where the code might be running in.

    Lastly, note that the computer's clock must be set correctly if you expect to get a valid result. Always synchronize your computer's clock to the Internet by using NTP or your OS's "Set date and time automatically" feature.