Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get current UTC offset of different timezones?

Tags:

c#

datetime

Problem: I Need to execute a task on a server that is on UTC at specific time in different time zones. Say for example I want to execute at 9:00AM Pacific Time, irrespective of Daylight Savings changes.

What do I have? I checked the enumeration of time zones by doing

var infos = TimeZoneInfo.GetSystemTimeZones();
foreach (var info in infos)
{
    Console.WriteLine(info.Id);
}

I could see only "Pacific Standard Time" for the pacific time for example and If I do the following,

TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time").GetUtcOffset(DateTime.UtcNow)

I get -07:00:00 as output but as of now the offset is -08. That means it doesn't consider the daylight changes.

I was planing to to create a DateTime instance based on the offset I get above, which doesn't seem to work as I expected.

Also, I can't use frameworks like NodaTime

Any idea how I can get it working?

like image 397
Amit Avatar asked Feb 12 '23 19:02

Amit


2 Answers

You've already got your answer, using TimeZoneInfo.GetUtcOffset and passing a DateTime with DateTimeKind.Utc will work.

I get -07:00:00 as output but as of now the offset is -08. That means it doesn't consider the daylight changes.

Actually, -7 is indeed the current offset, as Pacific time is currently using daylight saving time. In the winter, the offset reverts to -8, which is the standard offset. I think you just have them backwards.

Also, keep in mind that the Id property of a TimeZoneInfo object is the identifier for the entire time zone. Some of them are misleading, like "Pacific Standard Time" - which would make you believe that it only uses Pacific Standard Time (PST), but actually it represents the entire North American Pacific Time zone - including Pacific Standard Time and Pacific Daylight Time. It will switch offsets accordingly at the appropriate transitions.

like image 193
Matt Johnson-Pint Avatar answered Feb 15 '23 09:02

Matt Johnson-Pint


You are probably looking for something like this:

var chinaTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("China Standard Time"));
var pacificTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"));

The string passed to FindSystemTimeZoneById is picked form TimeZoneInfo.GetSystemTimeZones()

Update: cleansed the code

like image 27
nikib3ro Avatar answered Feb 15 '23 11:02

nikib3ro