How do I convert UTC to PST or PDT depending upon

2020-06-03 04:57发布

I cannot use DateTime.Now because the server is not necessarily located in Calfornia

标签: c# .net timezone
1条回答
Bombasti
2楼-- · 2020-06-03 05:27

Two options:

1) Use TimeZoneInfo and 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) Use my Noda Time project :)

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

Obviously I'm biased, but I prefer to use Noda Time, primarily for three reasons:

  • 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
查看更多
登录 后发表回答