2017-09-26 80 views
-3

我想將日期轉換爲上述格式。我曾經使用過: DateTime date1 = DateTime.ParseExact(date,「dd/MM/yyyy」,null); 但是,由於字符串未被識別爲有效的日期時間,因此它會給出例外。如何將日期格式dd MMM,yyyy轉換爲dd/MM/yyyy在mvc

注意:date是一個字符串數據類型,它是dd MMM,yyyy格式。

+1

[C#ASP.Net日期格式(可能的重複https://stackoverflow.com/questions/31458054/c-sharp- asp-net-date-format) – TheCog

回答

1

字符串未被識別爲有效的日期時間

因爲你試圖解析從這種格式的日期字符串:

"dd/MM/yyyy" 

但是,正如你的狀態,日期字符串是格式:

"dd MMM, yyyy" 

ParseExact意思就是說... 確切。從它在格式解析日期:

DateTime date1 = DateTime.ParseExact(date, "dd MMM, yyyy", null); 

然後你就可以輸出任何格式的價值,你喜歡:

date1.ToString("dd/MM/yyyy"); 
+0

這解決了我的問題。謝謝。 – Bibliophile

0

ParseExact取源格式爲第二個參數。嘗試使用DateTime.ParseExact(date, "dd MMM, yyyy", null);

0

@David擊敗了我的答案,但我只是想補充說,你應該使用TryParseExact而不是ParseExact。這樣,你就可以從潛在的問題中恢復過來。例如:

if (DateTime.TryParseExact(date, "dd MMM, yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime date2)) 
{ 
    date2.ToString("dd/MM/yyyy"); 
} 
else 
{ 
    // handle date in incorrect format 
} 
0

可以喲,請試試這個:

 string dateString = "15 Jun, 2017"; 
     DateTime result = DateTime.ParseExact(dateString, "dd MMM, yyyy", null); 

     // Changing to dd/MM/yyyy 
     string myDate = result.ToString("dd/MM/yyyy"); 
相關問題