2013-04-02 91 views
1

我有以下兩個字符串格式的日期。需要將以下字符串轉換爲時間格式

1. 06 Mar 2013 
2. 26 Mar 2013 

我需要在這兩個日期比較即if (06 Mar 2013 < 26 Mar 2013)

是否有任何內置函數的字符串轉換成C#日期和時間格式?

回答

2

您需要解析這兩個日期爲DateTime對象,使用DateTime.ParseExact與格式dd MMM yyyy,然後比較兩者。

string str1 = "06 Mar 2013"; 
string str2 = "26 Mar 2013"; 

DateTime dt1 = DateTime.ParseExact(str1, "dd MMM yyyy", null); 
DateTime dt2 = DateTime.ParseExact(str2, "dd MMM yyyy", null); 
if(dt1 < dt2) 
{ 
    //dt1 is less than dt2 
} 

您也可以使用格式d MMM yyyy,單d這將適用於單位和兩位數日以下列方式工作(例如02212等)

+1

謝謝搭檔...我被這個零件卡住了一段時間... :) –

+0

@ViVek,不客氣 – Habib

1

是的。嘗試使用DateTime.ParseDateTime.ParseExact方法。下面是代碼示例:

string first = "06 Mar 2013"; 
string second = "26 Mar 2013"; 

DateTime d1 = DateTime.Parse(first); 
DateTime d21 = DateTime.Parse(second); 

var result = d1 > d21; //false 
0

使用DateTime.ParseExact

DateTime dt = DateTime.ParseExact(str, "dd MMM yyyy", CultureInfo.InvariantCulture); 

Demo

需要

CultureInfo.InvariantCulture以確保即使當前文化沒有英文月份名稱,也能成功解析它。

相關問題