2010-12-14 82 views
3

我有一個程序,它將不規則的日期和時間字符串轉換爲系統日期時間。C#如何將不規則的日期和時間字符串轉換爲DateTime?

但是,由於系統無法識別不規則的字符串,因此.ParseExact,toDateTime和TryParse方法無法使用。

只有2種,該方案需要轉換日期時間字符串:

Thu Dec 9 05:12:42 2010 
Mon Dec 13 06:45:58 2010 

請注意,單日有,我已經使用了.replace方法將單日期轉換的雙重間距到Thu Dec 09 05:12:42 2010

可能有人請告訴代碼?謝謝!

的代碼:

 String rb = re.Replace(" ", " 0"); 

     DateTime time = DateTime.ParseExact(rb, "ddd MMM dd hh:mm:ss yyyy", CultureInfo.CurrentCulture); 

     Console.WriteLine(time.ToString("dddd, dd MMMM yyyy HH:mm:ss")); 

回答

5

我真的避免正則表達式和用什麼已經內置.NET(TryParseExact方法和date formats):

DateTime result; 
string dateToParse = "Thu Dec 9 05:12:42 2010"; 
string format = "ddd MMM d HH:mm:ss yyyy"; 

if (DateTime.TryParseExact(
    dateToParse, 
    format, 
    CultureInfo.InvariantCulture, 
    DateTimeStyles.AllowWhiteSpaces, 
    out result) 
) 
{ 
    // The date was successfully parsed => use the result here 
} 
+0

@Darin:正則表達式是隻存在於提取日期來自更大的字符串。看到他的[早期問題](http://stackoverflow.com/questions/4426597/c-how-to-retrieve-a-certain-text-located-within-a-string)。 – AgentConundrum 2010-12-14 07:29:27

+0

@AgentConundrum,從我可以看到他正在使用正則表達式來替換原始字符串中的空格,在一天的開始時添加0,等等......正確的格式字符串不需要的東西。 – 2010-12-14 07:31:25

+0

@Darin:你說得對。我掩飾了第二個正則表達式。對於那個很抱歉。 – AgentConundrum 2010-12-14 07:32:28

0

你應該捕捉你的日期時間的部分到匹配對象中的捕獲組中,然後以任何您想要的方式重新構建它們。

你可以使用這個表達式語句命名組,使其更容易

((?<day>)\w{3})\s+((?<month>)\w{3})\s+((?<date>)\d)\s((?<time>)[0-9:]+)\s+((?<year>)\d{4}) 
+0

你認真對待這個嗎? – 2010-12-14 07:42:00

0

這是示例代碼,你可以嘗試:

 var str = "Thu Dec 9 06:45:58 2010"; 
     if (str.IndexOf(" ") > -1) 
     { 
      str = str.Replace(" ", " "); 
      DateTime time = DateTime.ParseExact(str, "ddd MMM d hh:mm:ss yyyy", null); 
     } 
     else 
     { 
      DateTime time = DateTime.ParseExact(str, "ddd MMM dd hh:mm:ss yyyy", null); 
     } 
相關問題