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

标签 c# datetime time

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

但是由于系统不识别不规则字符串,.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/

相关文章:

c# - Instantiate 方法不会在 Canvas 内绘制预制按钮,也不会使用正确的预制尺寸绘制它

c# - 为什么 DateTime.ParseExact() 不能使用 “4/4/2010 4:20:00 PM” “M'/'d'/'yyyy H' :'mm' :'ss' 'tt” 解析 0x104567910 中的 AM/PM

java - Java 8 bean 日期属性使用什么类型 - Instant 或 ZoneDdateTime?

mysql - 安排事件并让事件跨越午夜

ios - 跟踪用户浏览 iOS 应用的 UI 所花费的时间

c# - 如何在统一的 XML 配置中将一个单例注册到不同的接口(interface)?

c# - 如何获取在方法单元测试中分配给 protected 对象的 HttpContext.Current.Server.MapPath 的假路径?

c# - Rfc2898DeriveBytes 和 TripleDes

python - 处理 panda to_datetime 函数中的时区

php - 使用 PHP 将 Facebook 时间转换为人类可读时间