簡體   English   中英

用DateTime.ParseExact解析時,字符串格式不正確

[英]String was not in a correct format when parsed with DateTime.ParseExact

當我嘗試將此字符串解析為日期時:

1.05.2016

使用此代碼:

var startDate = DateTime.ParseExact(Console.ReadLine(),
              "dd.m.yyyy", CultureInfo.InvariantCulture);

發生錯誤:

Unhandled Exception: System.FormatException: String was not recognized as a valid DateTime.
   at System.DateTimeParse.ParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style)
   at System.DateTime.ParseExact(String s, String format, IFormatProvider provider)
   at _09.Holidays_Between_Two_Dates.Program.Main(String[] args) in C:\Users\martin\documents\visual studio 2015\Projects\Methods. Debugging - Troubleshooting Code\09. Holidays Between Two Dates\09. Holidays Between Two Dates.cs:line 15

有人可以幫忙嗎? 提前致謝。

更正格式,因為輸入日期時間格式和提供的格式必須匹配

對於您的輸入1.05.2016您可以使用

var startDate = DateTime.ParseExact(Console.ReadLine(),
              "d.MM.yyyy", CultureInfo.InvariantCulture);

但日期並非總是單位數,因此最好使用兩位數01.05.2016

var startDate = DateTime.ParseExact(Console.ReadLine(),
              "dd.MM.yyyy", CultureInfo.InvariantCulture);

“ M”代表幾個月,“ m”代表分鍾。 確保使用正確的一個:

var startDate = DateTime.ParseExact(Console.ReadLine(),
             "dd.M.yyyy", CultureInfo.InvariantCulture);

您可以從Console.Readline()中仔細檢查您的輸入嗎? 也許其中包含回車符或其他一些非法字符? 我在LinqPad中運行了以下命令:

DateTime.ParseExact("1.05.2016","d.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture).Dump();

然后返回“ 01/05/2016 00:00:00”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM