Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/265.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何根据加利福尼亚州的当前时间将UTC转换为PST或PDT?_C#_.net_Timezone - Fatal编程技术网

C# 如何根据加利福尼亚州的当前时间将UTC转换为PST或PDT?

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

我无法使用日期时间。现在,因为服务器不一定位于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 = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
        var utcNow = DateTime.UtcNow;
        var pacificNow = TimeZoneInfo.ConvertTimeFromUtc(utcNow, zone);

        Console.WriteLine(pacificNow);
    }
}
2) 使用我的项目:)

显然我有偏见,但我更喜欢使用野田佳彦的时间,主要有三个原因:

  • 您可以使用TZDB时区信息,它在Windows之外更便于携带。(也可以使用基于BCL的分区。)
  • 不同类型的信息有不同的类型,这避免了
    DateTime
    试图表示三种不同类型的值的奇怪之处,也避免了仅仅表示“日期”或“一天中的某个时间”的概念
  • 它的设计考虑到了可测试性

即使是PDT,我如何将其强制为PSTcurrently@HaBo:我建议你问一个新问题,详细说明你想要达到的目标以及原因。例如,你可以找到一个全年都是太平洋标准时间的时区。
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);
    }
}