gpt4 book ai didi

C#如何将不规则的日期时间String转换成DateTime?

转载 作者:行者123 更新时间:2023-11-30 14:41:13 24 4
gpt4 key购买 nike

我有一个程序可以将不规则的日期和时间字符串转换为系统日期时间。

但是由于系统不识别不规则字符串,.ParseExact、toDateTime、TryParse等方法都没有生效。

程序需要转换的日期时间字符串只有两种:

 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"));

最佳答案

我真的会避免使用正则表达式并使用已经内置的 .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
}

关于C#如何将不规则的日期时间String转换成DateTime?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4436795/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com