2016-02-26 78 views
0

我有下面的一段代碼來記錄消息。由於我想每個date都有日誌,我嘗試檢索當前的date,然後嘗試使用path/dd_mm_yyyy_LogFile.txt格式創建具有該特定日期的日誌文件。在此之前,我必須無時間檢索當前date使用DateTime.ParseExact時字符串未被識別爲有效日期時間

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); 

但我得到字符串未被識別爲有效的DateTime。我跟着很多其他帖子,如將"dd_MM_yyyy"更改爲"dd-MM-yyy""d-m-yyyy",但不幸的是我仍然遇到同樣的錯誤。還有什麼在這裏失蹤?以下截圖供參考。如果您看到屏幕截圖,我會提取適當的d值。但仍然是上述例外。在Parse方法

enter image description here

+0

你試過'dd-MM-yyyy'嗎? –

+3

如果字符串是「2/26/2016」,那麼格式字符串是不是「MM/dd/yyyy」? – David

+0

你說「將」dd_MM_yyyy「更改爲」dd-MM-yyy「或」dm-yyyy「」 - 但屏幕截圖的日期格式爲「dd/MM/yyy」格式 – enkryptor

回答

1

這樣,而不是創建d

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

ToShortDateString()沒有你想要的格式。

+0

那麼這是一個很好的方法..也很容易..謝謝.. :) –

1

你的格式字符串應完全匹配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 
+0

我得到了我正在做的錯誤...謝謝你.. :) –

3

,我可以從圖片中看到,你真正想要"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); 
+0

我得到了我正在做的錯誤...謝謝你.. :) –

1

看您發佈的屏幕截圖。字符串的運行時間值爲:

"2/26/2016" 

所以格式化字符串應該是:

"M/dd/yyyy" 

或:

"MM/dd/yyyy" 

通過使用這些其他格式的字符串,你明確告訴該系統使用確切的格式。並且您擁有的字符串不符合該格式。因此錯誤。

+0

我得到了錯誤,我正在做...謝謝..: ) –

相關問題