【问题标题】:Parameter incorrect issue with DateTime.ParseExtractDateTime.ParseExtract 的参数不正确问题
【发布时间】:2013-11-08 15:19:40
【问题描述】:

我有以下行。 DateTime.ParseExact("08-11-2013 07:38:05", "yyyy-MM-dd HH:mm:ss", Nothing)

它会抛出一个错误。

参数不正确。

堆栈跟踪

在 System.DateTimeParse.ParseExact(String s, 字符串格式, DateTimeFormatInfo dtfi,DateTimeStyles 样式)在 System.DateTime.ParseExact(String s, String 格式, IFormatProvider 提供者)

提前致谢。

【问题讨论】:

    标签: c# .net datetime


    【解决方案1】:

    您的格式与您提供的日期不匹配,应该是:

    "dd-MM-yyyy HH:mm:ss"
    

    考虑到您指的是 2013 年 11 月 8 日

    你的代码应该是:

    DateTime dt = DateTime.ParseExact("08-11-2013 07:38:05", 
                                      "dd-MM-yyyy HH:mm:ss", 
                                       CultureInfo.InvariantCulture); // Instead of Nothing
    

    您也可以使用"d-M-yyyy HH:mm:ss" 格式,因为它会同时考虑一位数/两位数的日期和月份。

    另外您似乎来自 VB.Net 后台,其中 Nothing 是默认值,在 C# 中您可以使用 null 来处理您的情况,或者更好地使用 CultureInfo.InvariantCulture

    更多信息请见:Custom Date and Time Format Strings

    【讨论】:

    • 您应该在回答中添加他的第一次尝试是尝试获取年份(4 位数字)然后是月份(2 位数字)然后是日期(2 位数字),用“-”分隔。 . 他显然没有像你指出的那样做:)
    • @Noctis,您的评论将对 OP 有所帮助,我还添加了自定义日期和时间格式链接以获取更多详细信息。
    • 是的,你的答案是正确的,并且可能会是未来唯一阅读的内容:)
    猜你喜欢
    • 2021-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-07
    • 1970-01-01
    • 2020-03-13
    • 2021-01-11
    • 2023-04-11
    相关资源
    最近更新 更多