2010-12-14 81 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); 
     } 
相关问题