【问题标题】:Time parsing Issue using DateTime.ParseExact()使用 DateTime.ParseExact() 的时间解析问题
【发布时间】:2017-03-15 06:17:48
【问题描述】:

我有一个时间值存储为格式为HH:mm的字符串

我使用以下代码将其解析为今天日期的日期

DateTime.ParseExact("09:00","HH:mm",New System.Globalization.CultureInfi("En-GB"))

结果是2017-03-15 09:00:00

当从另一台机器运行此代码时,我得到以下结果:1899-12-31 09:00:00

我将我的代码替换为以下内容

DateTime.ParseExact(DateTime.Now.ToString("yyyy-MM-dd") & " 09:00","yyyy-MM-dd HH:mm",New System.Globalization.CultureInfi("En-GB"))

而且效果很好,但我仍然想知道为什么每个系统都将日期解析为不同的值???

【问题讨论】:

    标签: vb.net datetime ssis etl script-task


    【解决方案1】:

    DateTime.ParseExact 中缺少年/月/日的默认值
    来自 .NET 源代码:

    下表描述了获取默认值的行为 当缺少某个年/月/日值时。
    “X”表示该值存在。而“--”表示缺少该值。

    Year    Month   Day =>  ResultYear  ResultMonth     ResultDay       Note
    
    X       X       X       Parsed year Parsed month    Parsed day
    X       X       --      Parsed Year Parsed month    First day       If we have year and month, assume the first day of that month.
    X       --      X       Parsed year First month     Parsed day      If the month is missing, assume first month of that year.
    X       --      --      Parsed year First month     First day       If we have only the year, assume the first day of that year.
    
    --      X       X       CurrentYear Parsed month    Parsed day      If the year is missing, assume the current year.
    --      X       --      CurrentYear Parsed month    First day       If we have only a month value, assume the current year and current day.
    --      --      X       CurrentYear First month     Parsed day      If we have only a day value, assume current year and first month.
    --      --      --      CurrentYear Current month   Current day     So this means that if the date string only contains time, you will get current date.
    

    【讨论】:

    • 这很有帮助,但是为什么我从我的电脑中获得今天的价值??
    • 如果你没有在解析的字符串中提供年月日,那么你将从执行代码的机器上获取当前日期(今天)
    • 这有点令人困惑,为什么要在测试机上获得 1899-12-31??
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多