简体   繁体   English

无论夏令时如何,C# 中的太平洋时间

[英]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在夏令时 PT = PDT(太平洋夏令时)= UTC - 7
  • During Non Daylight saving times PT = PST (Pacific Standard Time 0 = UTC - 8在非夏令时 PT = PST(太平洋标准时间 0 = UTC - 8

I am using C# and do the following:我正在使用 C# 并执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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