2017-08-29 78 views
-2

我有2日期时间的:添加时间跨度只有日期,而不是日期的时间

DateTime beginDate = 2000/01/01 14:00 

DateTime endDate = 2000/01/01 14:30 

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

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添加到给定日期的时间?

+0

这是有点不清楚你想要做什么,为什么你跳过这么多篮球。 – Rotem

+0

通过使用beginDate和myValue来计算并获得与endDate相同的结果 – user1702369

+0

不清楚'myValue'是什么意思。如果'beginDate' +'myValue'应该等于'endDate',那么'myValue'应该等于'span'。为什么所有的'.TimeOfDay','.Date','。Minutes','.Ticks'混淆?如果您只是试图序列化TimeSpan来保存数据库,请使用'.Ticks'属性。 – Rotem

回答

2

您应该使用TimeSpan.TotalMinutes

span.Minutes只给你分钟部分。所以1:30它不会是90.它会是30。使用TotalMinutes可获得90

另外beginDate.Date应该更改为beginDate,因为通过使用Date您正在删除时间。

1
DateTime otherDate = beginDate + span; 
+0

我必须使用myValue和beginDate来计算。我更新了我的帖子。因为我在数据库中保存了myValue和beginDate,在稍后的阶段和另一个类中,我从数据库中检索这两个字段,然后必须使用它们返回endDate – user1702369