-2

I have 2 DateTime's:

DateTime beginDate = 2000/01/01 14:00

DateTime endDate =  2000/01/01 14:30

I calculate a timespan between these 2 hours:

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 ) )

The Problem is I keep on getting 0:30 back and I should get back 14:30. I understand why, its because beginDate.Date gives you 2000/01/01 00:00, but I cant use beginDate.TimeOfDay.Add because it is a readonly field. How do I achieve that it only add the myValue to the time of the given date??

user1702369
  • 1,089
  • 2
  • 13
  • 31
  • It's a bit unclear what you're trying to do and why you're jumping through so many hoops. – Rotem Aug 29 '17 at 09:59
  • By using the beginDate and myValue to calculate and get the same result as the endDate – user1702369 Aug 29 '17 at 10:06
  • Unclear what `myValue` is meant to represent. By all logic if `beginDate` + `myValue` should be equal to `endDate` then `myValue` should be equal to `span`. Why all the `.TimeOfDay`, `.Date`, `.Minutes`, `.Ticks` confusion? If you're just trying to serialize a `TimeSpan` for saving in a database, use the `.Ticks` property and no more. – Rotem Aug 29 '17 at 10:18

2 Answers2

2

You should use TimeSpan.TotalMinutes.

span.Minutes only gives you the minutes part. So of 1:30 it won't be 90. It'll be 30. Use TotalMinutes to get the 90.

Also beginDate.Date should be changed to beginDate because by using Date you are removing the time.

ispiro
  • 26,556
  • 38
  • 136
  • 291
1
DateTime otherDate = beginDate + span;
Derek
  • 7,615
  • 5
  • 33
  • 58
  • I have to use myValue and beginDate to calculate. I've updated my post. Its because I save myValue and beginDate in the DB, at a later stage and in another class I retrieve these 2 fields out of the DB and then must use them to result back to the endDate – user1702369 Aug 29 '17 at 10:03