如何转换UTC到PST或PDT根据目前的时间是在加利福尼亚州是什么?加利福尼亚州、是在、根据、目前

2023-09-03 17:07:15 作者:抢我辣条你别跑

我不能使用 DateTime.Now ,因为服务器不一定位于Calfornia

I cannot use DateTime.Now because the server is not necessarily located in 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)使用我的野田佳彦时间项目:)

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

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

您可以使用TZDB时区信息,这是更便携之外的Windows。 (您可以使用BCL基带过。) 有不同类型的各种不同类型的信息,避免了日期时间的古怪试图重新present三种不同的值,和不具有概念刚刚重新presenting日期或一天的时间 在它的设计与可测试性考虑 You can use the TZDB time zone information, which is more portable outside Windows. (You can use BCL-based zones too.) There are different types for various different kinds of information, which avoids the oddities of DateTime trying to represent three different kinds of value, and having no concept of just representing "a date" or "a time of day" It's designed with testability in mind