C# 如何根据加利福尼亚州的当前时间将UTC转换为PST或PDT?
我无法使用日期时间。现在,因为服务器不一定位于Calfornia两个选项: 1) 使用C# 如何根据加利福尼亚州的当前时间将UTC转换为PST或PDT?,c#,.net,timezone,C#,.net,Timezone,我无法使用日期时间。现在,因为服务器不一定位于Calfornia两个选项: 1) 使用TimeZoneInfo和DateTime: using System; class Test { static void Main() { // Don't be fooled - this really is the Pacific time zone, // not just standard time... var zone = Time
TimeZoneInfo
和DateTime
:
using System;
class Test
{
static void Main()
{
// Don't be fooled - this really is the Pacific time zone,
// not just standard time...
var zone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
var utcNow = DateTime.UtcNow;
var pacificNow = TimeZoneInfo.ConvertTimeFromUtc(utcNow, zone);
Console.WriteLine(pacificNow);
}
}
2) 使用我的项目:)
显然我有偏见,但我更喜欢使用野田佳彦的时间,主要有三个原因:
- 您可以使用TZDB时区信息,它在Windows之外更便于携带。(也可以使用基于BCL的分区。)
- 不同类型的信息有不同的类型,这避免了
试图表示三种不同类型的值的奇怪之处,也避免了仅仅表示“日期”或“一天中的某个时间”的概念DateTime
- 它的设计考虑到了可测试性
using System;
using NodaTime;
class Test
{
static void Main()
{
// TZDB ID for Pacific time
DateTimeZone zone = DateTimeZoneProviders.Tzdb["America/Los_Angeles"];
// SystemClock implements IClock; you'd normally inject it
// for testability
Instant now = SystemClock.Instance.Now;
ZonedDateTime pacificNow = now.InZone(zone);
Console.WriteLine(pacificNow);
}
}