【问题标题】:Sum two dates represented in a hh:mm:ss string format [duplicate]以 hh:mm:ss 字符串格式表示的两个日期相加[重复]
【发布时间】:2016-01-28 19:20:58
【问题描述】:

我怎样才能把 2 次放在一起 我希望它保持时间格式:hh:mm:ss

string time1 = "00:49:35";
string time2 = "00:31:34";

totaltime = time1 + time2;

这应该是结果 01:21:09(1 小时 21 分 09 秒)

【问题讨论】:

  • 你想要的输出是什么?
  • 先做一个 SO 搜索怎么样?就像例如“Adding two DateTime objects together”。
  • 您将数据与表示混淆了。如果您的输入是字符串,则需要将其解析为合理的格式(例如 TimeSpan),然后添加它们,然后以您想要的表示形式打印时间跨度。
  • 结帐DateTimeTimeSpan SO中有成千上万个这样的问题
  • 2 次一起 01:21:09(1 小时 21 分 09 秒)

标签: c# datetime


【解决方案1】:

如何使用TimeSpan 类:

TimeSpan time1 = TimeSpan.Parse("00:49:35");
TimeSpan time2 = TimeSpan.Parse("00:31:34");

TimeSpan res = time1 + time2;

Console.WriteLine(res.ToString()); // 01:21:09, you may omit the ToString() call

如果你不想Parse一个字符串,你可以构造一个TimeSpan对象:

TimeSpan time1 = new TimeSpan(00, 49 ,35);
TimeSpan time2 = new TimeSpan(00, 31 ,34);
TimeSpan res = time1 + time2;
Console.WriteLine(res); // 01:21:09

【讨论】:

    【解决方案2】:

    这对我有用:

    (TimeSpan.Parse(time1) + TimeSpan.Parse(time2)).ToString()
    

    【讨论】:

      猜你喜欢
      • 2015-07-21
      • 2016-02-08
      • 1970-01-01
      • 1970-01-01
      • 2012-05-09
      • 2012-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多