【问题标题】:How do I convert UTC to PST or PDT depending upon what the current time is in California?如何根据加利福尼亚的当前时间将 UTC 转换为 PST 或 PDT?
【发布时间】:2013-02-07 10:58:06
【问题描述】:

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

【问题讨论】:

    标签: c# .net timezone


    【解决方案1】:

    两种选择:

    1) 使用TimeZoneInfoDateTime

    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) 使用我的Noda Time 项目:)

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

    显然我有偏见,但我更喜欢使用 Noda Time,主要有以下三个原因:

    • 您可以使用 TZDB 时区信息,它在 Windows 之外更易于移植。 (您也可以使用基于 BCL 的区域。)
    • 各种不同的信息有不同的类型,避免了DateTime试图表示三种不同的值,没有只表示“日期”或“一天中的时间”的概念
    • 在设计时考虑了可测试性

    【讨论】:

    • 即使当前是 PDT,我如何强制它到 PST
    • @HaBo:我建议您提出一个新问题,详细说明您要实现的目标以及原因。例如,您可能能够找到全年都是 PST 的时区。
    猜你喜欢
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    • 2021-09-05
    • 2011-09-23
    相关资源
    最近更新 更多