簡體   English   中英

使用DateTime.ParseExact時,字符串未被識別為有效的DateTime

[英]String was not recognized as a valid DateTime when using DateTime.ParseExact

我有下面的代碼來記錄消息。 由於我想獲取每個date的日志,因此嘗試檢索當前date ,然后嘗試使用path/dd_mm_yyyy_LogFile.txt格式創建具有該特定日期的日志文件。 在此之前,我不得不沒有時間來獲取當前date

StreamWrite sw=null;
var d = Convert.ToString(DateTime.Today.ToShortDateString());
var date = DateTime.ParseExact(d, "dd_MM_yyyy", CultureInfo.InvariantCulture);
//Error in the above line  
sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\" + d + "_LogFile.txt", true);
sw.WriteLine(DateTime.Now.ToString() + ": " + message);

但是獲取String未被識別為有效的DateTime 我關注了許多其他帖子,例如將"dd_MM_yyyy"更改為"dd-MM-yyy""dm-yyyy"但不幸的是仍然遇到相同的錯誤。 這里還缺少什么? 下面的截圖供參考。 如果您看到屏幕截圖,則說明已獲取適當的d值。 但還是以上例外。

在此處輸入圖片說明

從圖片中可以看到,您實際上需要"M/d/yyyy"格式:

  String d = @"2/26/2016"; // d's value has been taken from the screenshot
  DateTime date = DateTime.ParseExact(d, "M/d/yyyy", CultureInfo.InvariantCulture);

您在Parse方法中使用的格式字符串應與ToShortDateString生成的格式字符串完全匹配。 例如,這與我一起工作:

var d = Convert.ToString(DateTime.Today.ToShortDateString());
Console.WriteLine(d);

var date = DateTime.ParseExact(d, @"MM/dd/yyyy", CultureInfo.InvariantCulture);
Console.WriteLine(date);

輸出:

02/26/2016                                                                                                                                                                                                                                             
02/26/2016 00:00:00

查看您發布的屏幕截圖。 字符串的運行時值為:

"2/26/2016"

因此,格式字符串應為:

"M/dd/yyyy"

要么:

"MM/dd/yyyy"

通過使用其他格式字符串,您可以明確地告訴系統使用該確切格式。 而且您的字符串與該格式不匹配。 因此,錯誤。

像這樣創建d

var d = DateTime.Today.ToString("dd_MM_yyyy");

ToShortDateString()沒有所需的格式。

暫無
暫無

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

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