使用c#中的addHours()添加到目前为止的持续时间

时间:2017-04-12 20:25:38

标签: c# datetime duration

我想在我的datetime变量中添加持续时间。我正在从csv文件中读取持续时间。持续时间的格式为0:29:40或1:29:40。当我将此添加到datetime变量时,它会提供不正确格式的异常。如何使用此格式添加持续时间。以前我的持续时间是一个简单的整数,如“6”或“7”,但现在格式为“0:29:40”我不知道如何更改我的代码以适应这种格式。

以前我这样做

 double hours = Convert.ToDouble(row.Cells[2].Value.ToString());
            DateTime newdate = finaldate.AddHours(hours);

row.Cells[2].Value.ToString()从csv

中读取值

感谢任何帮助,谢谢

2 个答案:

答案 0 :(得分:3)

您不需要解析为double。解析为TimeSpan。类似的东西:

var source = "0:29:40";
var ts = TimeSpan.Parse(source);

现在ts是你的时间跨度。 TimeSpan的好处是你可以将其添加到DateTime

DateTime newdate = finaldate + ts;

答案 1 :(得分:2)

您需要使用TimeSpan.Parse()TimeSpan.ParseExact()方法正确解析字符串,然后只需将TimeSpan结果添加到现有日期:

var time = TimeSpan.Parse(row.Cells[2].Value.ToString());
DateTime newDate = finalDate.Add(time);

如果您需要明确指定每个时间值代表的内容,那么TimeSpan.ParseExact()方法将允许您提供格式字符串来指定:

// This will assume that 1:29:40 is hours, minutes, and seconds
var time = TimeSpan.ParseExact(row.Cells[2].Value.ToString(), @"h\:m\:s", null); 
相关问题