【问题标题】:Where does DateTime.ToLocalTime() get offsetDateTime.ToLocalTime() 在哪里获得偏移量
【发布时间】:2014-02-22 09:45:33
【问题描述】:

这是一个简单的代码:

System.DateTime dt = new DateTime(635267088000000000);
Console.WriteLine(dt.ToLocalTime());

我在 Windows“区域和语言设置”中更改了位置、格式和系统区域设置,但结果没有改变。

我已重新启动计算机。我正在使用 Windows 7。

【问题讨论】:

    标签: c# .net


    【解决方案1】:

    系统 Timzone 设置位于“日期和时间”控制面板中,而不是“区域和语言”控制面板(令人困惑的是,这也是键盘语言设置所在的位置,而不是键盘控制面板)。

    【讨论】:

    • 谢谢。它对我有帮助!
    【解决方案2】:

    奇怪...您提供的代码无法了解本地信息,因为您没有指定本地的种类。要利用转换为本地时间或通用时间的优势,您必须指定 DateTime 对象的类型,如下所示:

    DateTime dtUtc = new DateTime(DateTime.UtcNow.Ticks, DateTimeKind.Utc);
    DateTime dtLocal = dtUtc.ToLocalTime();
    Console.WriteLine("{0} - {1}", dtUtc, dtLocal); 
    

    这将输出如下内容:

    22/2/2014 10:25:59 - 22/2/2014 14:25:59
    

    请注意,如果您使用DateTime.Now 或DateTime.UtcNow,它们已经分别具有DateTimeKind.Local 或DateTimeKind.Utc 的种类信息。

    DateTime dt = DateTime.Now;
    Console.WriteLine(dt.Kind);
    dt = DateTime.UtcNow;
    Console.WriteLine(dt.Kind);
    dt = new DateTime(635267088000000000);
    Console.WriteLine(dt.Kind);
    

    输出是:

    Local
    Utc
    Unspecified
    

    探索这个例子。

    DateTime dt = new DateTime(635267088000000000); // same as DateTimeKind.Unspecified
    DateTime dtUtc = dt.ToUniversalTime();
    DateTime dtLocal = dt.ToLocalTime();
    Console.WriteLine("{0} - {1} - {2}", dt, dtUtc, dtLocal);
    
    dt = new DateTime(635267088000000000, DateTimeKind.Local);
    dtUtc = dt.ToUniversalTime();
    dtLocal = dt.ToLocalTime();
    Console.WriteLine("{0} - {1} - {2}", dt, dtUtc, dtLocal);
    
    dt = new DateTime(635267088000000000, DateTimeKind.Utc);
    dtUtc = dt.ToUniversalTime();
    dtLocal = dt.ToLocalTime();
    Console.WriteLine("{0} - {1} - {2}", dt, dtUtc, dtLocal); 
    

    【讨论】:

    • 我不知道为什么,但你的例子给了我“22.02.2014 11:55:47 - 22.02.2014 17:55:47”
    • 如果我使用 DateTimeKind.Local 作为第二个参数,那么 dtUtc 和 dtLocal 将是相同的。看起来 DateTimeKind.Utc 是第二个参数的默认值。
    • I don't know why, but your example give me "22.02.2014 11:55:47 - 22.02.2014 17:55:47" 这意味着你在 UTC +6 时区。
    • If I use DateTimeKind.Local as the second parameters, than dtUtc and dtLocal will be the same.你在哪里困惑?如果您已指定 DateTimeKind.Local 您的日期时间是本地的,那么将其转换为本地将给出相同的结果,因为它已经是本地的。
    • 当DateTime 的类型未指定时,在转换时它会加倍处理。查看更新答案中的示例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-19
    • 2017-02-21
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    相关资源
    最近更新 更多