如何转换UTC到PST或PDT根据目前的时间是在加利福尼亚州是什么? [英] How do I convert UTC to PST or PDT depending upon what the current time is in California?

查看:996
本文介绍了如何转换UTC到PST或PDT根据目前的时间是在加利福尼亚州是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能使用 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

这篇关于如何转换UTC到PST或PDT根据目前的时间是在加利福尼亚州是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆