仅将 TimeSpan 添加到日期时间而不是日期
Adding TimeSpan only to Time of Date and not Date
我有 2 个日期时间:
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 添加到给定日期的时间?
DateTime otherDate = beginDate + span;
你应该使用 TimeSpan.TotalMinutes。
span.Minutes
只给你分钟部分。所以 1:30
不会是 90。它会是 30
。使用 TotalMinutes
得到 90
.
另外 beginDate.Date
应更改为 beginDate
,因为使用 Date
会删除时间。
我有 2 个日期时间:
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 添加到给定日期的时间?
DateTime otherDate = beginDate + span;
你应该使用 TimeSpan.TotalMinutes。
span.Minutes
只给你分钟部分。所以 1:30
不会是 90。它会是 30
。使用 TotalMinutes
得到 90
.
另外 beginDate.Date
应更改为 beginDate
,因为使用 Date
会删除时间。