C#如何不规则的日期和时间字符串转换为日期时间? [英] C# How to convert irregular date and time String into DateTime?
问题描述
我有一个程序,将不规则的日期和时间字符串转换为系统DateTime。
I have a program which converts a irregular date and time string into a system DateTime.
但是,由于系统无法识别不规则字符串,因此.ParseExact,toDateTime和TryParse方法无效。
However as the system does not recognize irregular strings, the method .ParseExact, toDateTime and TryParse has not worked.
程序需要转换的日期时间字符串只有两种类型:
There are only 2 types of date time strings that the program needs to convert:
Thu Dec 9 05:12:42 2010
Mon Dec 13 06:45:58 2010
请注意,双重间距,我使用.replace方法将单个日期转换为 Thu Dec 09 05:12:42 2010
。
Please note that the single date has a double spacing which I have used the .replace method to convert the single date to Thu Dec 09 05:12:42 2010
.
有人可以请你提供代码吗?非常感谢!
May someone please advise on the codes? Thanks!
代码:
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"));
推荐答案
我真的会避免regex,在.NET( TryParseExact 方法和日期格式):
I would really avoid regex and use what's already built-in .NET (TryParseExact method and 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
}
这篇关于C#如何不规则的日期和时间字符串转换为日期时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!