c# - DateTime 到 Unix 时间转换不一致且 24 小时输入错误

标签 c# datetime timezone unix-timestamp dst

附件是我当前正在使用的方法,它接受DateTime字符串列表及其输入格式(即yyyy-MM-dd HH:mm:ss) ,以及以小时为单位的偏移量。

至于文化和“标准”,我正在使用 InvariantCulture 并将时间转换为 UTC

    public int unixFormat3(string dateTimeInput, string inputFormat, int hours)
    {
        DateTime result;
        CultureInfo provider = CultureInfo.InvariantCulture;
        result = DateTime.ParseExact(dateTimeInput, inputFormat, provider);

        int unixTime = (Int32)(result.ToUniversalTime().AddHours(hours).Subtract(new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc))).TotalSeconds;
        return unixTime;
    }

上述方法的两个问题:

  1. 我使用这个网站作为比较。如果我的输入是 2014-03-18 21:00:00,根据我的方法,我的输出是 1395190800,它会转换回 2014-03 -19 01:00:00 。有四个小时的时差。所需的输出是这样的:

enter image description here

  • 如果我的输入是 2014-03-18 24:00:00,我会收到以下错误:
  • 日历 System.Globalization.GregorianCalendar 不支持字符串表示的 DateTime。

    值得注意的是,它不允许在HH部分输入24。这是一个奇怪的错误,因为 NodaTime 处理得很好......尽管这与我使用 DateTime 无关。

    有人对这个领域有深入的了解吗?

    编辑:

    经过一些实验,删除 .ToUniversalTime() 会删除我的 4 小时偏移。为什么会发生这种情况?

    public int unixFormat3(string dateTimeInput, string inputFormat, int hours)
    {
        DateTime result;
        CultureInfo provider = CultureInfo.InvariantCulture;
        result = DateTime.ParseExact(dateTimeInput, inputFormat, provider);
    
        int unixTime = (Int32)(result.AddHours(hours).Subtract(new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc))).TotalSeconds;
        return unixTime;
    }
    

    最佳答案

    本文档,http://www.w3.org/TR/NOTE-datetime ,在这个问题中引用How to know whether a given string is a valid UTC DateTime format?未将 24 列为有效小时值。

    本文档,http://en.wikipedia.org/wiki/Iso8601 ,问题的答案引用的确实将 24:00 列为有效时间。这个,http://en.wikipedia.org/wiki/12-hour_clock#Confusion_at_noon_and_midnight ,还表示 24:00 有效。

    关于c# - DateTime 到 Unix 时间转换不一致且 24 小时输入错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22612127/

    相关文章:

    python - ElasticSearch日期格式,支持小数秒

    java - 如果时间戳映射到数据库/从数据库映射,则 Timestamp#equals() 失败

    python - Python 中的日期计算

    PostgreSQL UTC 至 CET/CEST

    c# - 如何在 Selenium 中自动接受 Chrome 的 "Always open these types of links in the associated app"对话框

    c# - MVVM 中的什么使它对托管 WPF 和 Silverlight 特别有吸引力,但对 native C++ 却没有吸引力?

    用于源代码格式化的 C#/.NET 库,就像 Stack Overflow 使用的那样?

    c# - 模板抽象类在字典中有值

    Python:只需打印 datetime.now() 包括正确的时区

    javascript - 如何使用 Javascript/jquery 设置浏览器的时区