4

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?

InteXX
  • 6,135
  • 6
  • 43
  • 80
Amit
  • 25,106
  • 25
  • 75
  • 116
  • 1
    Look at [this SO Question](http://stackoverflow.com/questions/2961848/how-to-use-timezoneinfo-to-get-local-time-during-daylight-savings-time) – Icemanind Jun 05 '14 at 20:47
  • 1
    At the moment I believe Pacific Time *is* UTC-7. It's UTC-8 during Standard Time, but we're on Daylight Saving Time at the moment. – pmcoltrane Jun 05 '14 at 20:56

2 Answers2

6

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.

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
2

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

Amit
  • 25,106
  • 25
  • 75
  • 116
nikib3ro
  • 20,366
  • 24
  • 120
  • 181