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

C#插入时间到SQL数据库时出现‘String was not recognized as a valid TimeSpan’错误

问题解决:TimeSpan.Parse报错及时间存储正确做法

错误根源

你的代码TimeSpan.Parse(string.Format(DateTime.Now.ToShortTimeString(), "hh:Mi"))存在两个核心问题:

  • string.Format参数顺序完全颠倒:第一个参数应为格式字符串,第二个才是要格式化的对象,参数错位导致生成的字符串完全不符合TimeSpan解析规则。
  • 冗余调用ToShortTimeString():该方法已返回本地化的短时间字符串,再套string.Format只会生成混乱内容,自然触发解析失败。

正确解决方案

方案1:直接用TimeSpan值插入数据库(推荐)

SQL的时间类型(如SQL Server的time)与.NET的TimeSpan直接对应,无需转字符串,直接取当前时间的TimeOfDay即可:

TimeSpan currentTime = DateTime.Now.TimeOfDay;
// 直接将currentTime作为参数传入SQL插入命令

这种方式彻底规避字符串格式问题,是最可靠的实现方式。

方案2:生成指定格式字符串后解析(仅特殊场景使用)

如果必须生成18:33或07:22 PM格式的字符串再转TimeSpan,需用ParseExact明确指定格式和文化信息,避免本地化干扰:

  • 24小时制格式解析:
string timeStr24 = DateTime.Now.ToString("HH:mm", CultureInfo.InvariantCulture);
TimeSpan timeSpan24 = TimeSpan.ParseExact(timeStr24, "HH\\:mm", CultureInfo.InvariantCulture);
  • 12小时制带AM/PM格式解析:
string timeStr12 = DateTime.Now.ToString("hh:mm tt", CultureInfo.InvariantCulture);
TimeSpan timeSpan12 = TimeSpan.ParseExact(timeStr12, "hh\\:mm tt", CultureInfo.InvariantCulture);

额外提醒

不要在SQL数据库中存储时间字符串,优先使用数据库原生时间类型(如time、datetime),既节省存储资源,也方便后续的时间查询、排序和计算操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 02:32:06