简体   繁体   中英

Pacific Time in C# regardless of daylight saving time

I need to ALWAYS stamp my DB with Pacific Time, regardless if it's August or February. Pacific Time is, the actual US west coast time at anytime of the year:

  • During Daylight saving times PT = PDT (Pacific Daylight time) = UTC - 7
  • During Non Daylight saving times PT = PST (Pacific Standard Time 0 = UTC - 8

I am using C# and do the following:

TimeZoneInfo pacificZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
CreatedDate = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, pacificZone);

Would that automatically take into account Daylight saving times, or do I need to account for this by doing this:

TimeZoneInfo pacificZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
CreatedDate = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, pacificZone);
if (!TimeZoneInfo.Local.IsDaylightSavingTime(CreatedDate))
{
       CreatedDate = CreatedDate.AddHours(-1);
}

Is my first or 2nd code snippet the correct one?

The first block is the correct one.


Test code

var utcDateDuringDaylightSavingsTime = new DateTime(2018, 7, 1, 15, 30, 30, DateTimeKind.Utc);
TimeZoneInfo pacificZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
var localDateDuringDaylightSavingsTime = TimeZoneInfo.ConvertTimeFromUtc(utcDateDuringDaylightSavingsTime, pacificZone);
var localDateNotDuringDaylightSavingsTime = TimeZoneInfo.ConvertTimeFromUtc(utcDateDuringDaylightSavingsTime.AddMonths(5), pacificZone);

Console.WriteLine(utcDateDuringDaylightSavingsTime.ToString("o") + "\t\tUTC");
Console.WriteLine(localDateDuringDaylightSavingsTime.ToString("o") + "\t\t Local during daylight saving");
Console.WriteLine(localDateNotDuringDaylightSavingsTime.ToString("o") + "\t\t Local not during daylight saving");

Output

2018-07-01T15:30:30.0000000Z        UTC
2018-07-01T08:30:30.0000000         Local during daylight saving
2018-12-01T07:30:30.0000000         Local not during daylight saving

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM