You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Convert.ToDateTime无法转换日/月/年格式时间字符串求助

解决C#日期解析FormatException问题

出现System.FormatException是因为Convert.ToDateTime默认使用当前线程的文化设置解析日期,而你的日期字符串格式是日.月.年 时:分:秒,如果当前文化的日期格式(比如en-US的月/日/年)不匹配,就会抛出异常。

以下是两种可靠的解决方法:

方法一:指定精确格式解析

使用DateTime.ParseExact或DateTime.TryParseExact明确指定日期字符串的格式,避免文化差异影响:

using System.Globalization;

// ParseExact直接解析,格式不匹配会抛出异常
DateTime date = DateTime.ParseExact("28.12.2022 13:45:04", "dd.MM.yyyy HH:mm:ss", CultureInfo.InvariantCulture);
Console.WriteLine(date);

// TryParseExact更安全,不会抛出异常,返回解析是否成功
if (DateTime.TryParseExact("28.12.2022 13:45:04", "dd.MM.yyyy HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime result))
{
    Console.WriteLine(result);
}
else
{
    Console.WriteLine("日期格式无效");
}

格式符说明:

  • dd:两位数字表示的日
  • MM:两位数字表示的月
  • yyyy:四位数字表示的年
  • HH:24小时制的两位数字小时
  • mm:两位数字表示的分
  • ss:两位数字表示的秒

方法二:匹配对应文化解析

如果你的日期格式符合特定地区的文化习惯(比如欧洲部分地区用dd.MM.yyyy),可以直接指定该文化进行解析:

using System.Globalization;

DateTime date = Convert.ToDateTime("28.12.2022 13:45:04", new CultureInfo("de-DE"));
Console.WriteLine(date);

内容的提问来源于stack exchange,提问作者CodeInSpace

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 17:40:17