仅将TimeSpan添加到日期时间而不是日期

时间:2017-08-29 09:52:42

标签: c# datetime timespan

我有2个DateTime:

DateTime beginDate = 2000/01/01 14:00

DateTime endDate =  2000/01/01 14:30

我计算这两小时之间的时间跨度:

TimeSpan span = endDate.Subtract(beginDate);
var myValue = beginDate.AddMinutes( span.Minutes ).TimeOfDay.Ticks

//Trying to get this equal to the endDate by using the beginDate + myValue
//I have to use myvalue, because this value comes from the DB and this piece 
//of code sits in another class than the above code
DateTime otherDate = beginDate.Date.Add( new TimeSpan( myValue ) )

问题是我继续0:30回来,我应该回到14:30。 我理解为什么,因为beginDate.Date给你2000/01/01 00:00,但我不能使用beginDate.TimeOfDay.Add,因为它是一个只读字段。 我如何实现它只将myValue添加到给定日期的时间?

2 个答案:

答案 0 :(得分:2)

您应该使用TimeSpan.TotalMinutes

span.Minutes只为您提供分钟部分。因此1:30它不会是90.它将是30。使用TotalMinutes获取90

此外beginDate.Date也应更改为beginDate,因为使用Date即可删除时间。

答案 1 :(得分:1)

DateTime otherDate = beginDate + span;
相关问题