C#中的太平洋时间,不考虑夏令时

时间:2018-10-16 18:06:48

标签: c# .net

无论是8月还是2月,我都必须始终用太平洋时间给我的数据库盖章。 太平洋时间是一年中任何时候的美国西海岸实际时间:

  • 夏令时PT = PDT(太平洋夏令时)= UTC-7
  • 在非夏时制时间PT = PST(太平洋标准时间0 = UTC-8

我正在使用C#并执行以下操作:

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

是否会自动考虑夏令时,还是我需要通过以下方式对此加以考虑:

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

1 个答案:

答案 0 :(得分:2)

  

我的第一个或第二个代码段正确吗?

第一个块是正确的。


测试代码

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");

输出

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