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

C#中将文本时间转为DateTime变量并实现加两周操作的方法

C# 时间处理常见问题解决方案

1. 文本格式时间转换为DateTime类型

常用的转换方法有三种,可根据场景选择:

  • 格式符合系统默认规则的场景,直接用DateTime.Parse()
    string dateStr = "2000/01/01";
    DateTime date = DateTime.Parse(dateStr);
    
  • 需要严格匹配指定格式、不受系统区域设置影响的场景,用DateTime.ParseExact(),需要引入命名空间using System.Globalization;
    string dateStr = "2000/01/01";
    DateTime date = DateTime.ParseExact(dateStr, "yyyy/MM/dd", CultureInfo.InvariantCulture);
    
  • 不确定文本格式是否合法、不想抛出异常的场景,用DateTime.TryParse()/DateTime.TryParseExact()
    string dateStr = "2000/01/01";
    if (DateTime.TryParse(dateStr, out DateTime date))
    {
        // 转换成功,可直接使用date变量
    }
    else
    {
        // 转换失败,执行错误处理逻辑
    }
    

2. 向DateTime变量添加两周时长

DateTime结构体内置了时间间隔计算方法,两周对应14天,直接调用AddDays()方法即可:

DateTime originalDate = new DateTime(2000, 1, 1);
// 加14天即两周,得到结果为2000/01/15 00:00:00
DateTime resultDate = originalDate.AddDays(14);

// 如果需要得到你示例中的2000/01/14结果,将参数调整为13即可,对应计算时排除起始日当天

如果需要更灵活的周数计算,也可以用Add()方法传入TimeSpan对象:

DateTime resultDate = originalDate.Add(TimeSpan.FromDays(14));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 14:36:01