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

C# DateTime与字符串转换时空字符串的默认日期设置方案

解决方案

核心实现思路

使用DateTime.TryParse()方法替代Convert.ToDateTime(),前者不会在转换失败时抛出异常,而是返回布尔值标识转换结果,你可以根据转换结果决定是使用转换后的值还是预设的默认日期。

代码实现示例

基础写法

var from = "";
DateTime StartDTime;
// 可自定义默认值,比如 new DateTime(1970,1,1)、DateTime.Now 等
DateTime defaultDate = new DateTime(2000, 1, 1);

if (!DateTime.TryParse(from, out StartDTime))
{
    StartDTime = defaultDate;
}

单行简洁写法(C# 7.0及以上版本支持)

var from = "";
DateTime defaultDate = new DateTime(2000, 1, 1);
DateTime StartDTime = DateTime.TryParse(from, out var tempDate) ? tempDate : defaultDate;

额外说明

  • 如果对日期格式有严格要求,比如只接受yyyy-MM-dd格式的字符串,可以使用DateTime.TryParseExact()方法指定格式,避免非预期的格式转换成功:
var from = "";
DateTime defaultDate = new DateTime(2000, 1, 1);
DateTime StartDTime = DateTime.TryParseExact(from, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out var tempDate) ? tempDate : defaultDate;
  • 默认日期可以根据业务需求自行调整,常用的默认值包括DateTime.MinValue、DateTime.Now、DateTime.Today或者自定义固定日期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 22:06:02