I thought this would be easier, but it hasn't been so far. I am trying to retrieve a datetime field from a stored procedure and compare it to the current DateTime.Now to get a timespan in minutes. However, when I use the code below, it returns a value that is not correct.
timespan = SqlFunctions.DateDiff("minute", c.dtimecre.Value, DateTime.Now).Value.ToString()
Assuming DateTime.Now is ‘2022-11-30 08:37:39.487’ and dtimecre is ‘2022-11-29 21:07:59.650’ – I expected to get a value of 689 but this is returning 750, not sure what I am doing wrong here.
CodePudding user response:
you can use datetime.subtract and get TotalMinutes
DateTime dt1 = DateTime.Parse("2022-11-29 21:07:59.650");
DateTime dt2 = DateTime.Parse("2022-11-30 08:37:39.487");
var result =dt2.Subtract(dt1).TotalMinutes; // reslt = 689.66395
CodePudding user response:
Make sure DateTime.Now
and c.dtimecre.Value
time zones are same. If there are differences, then the DateDiff
function's result could be incorrect.
If not sure try to use TimeSpan.TotalMinutes
property to calculate the time difference between the two DateTime values in minutes. That's not required to convert DateTime
to a specific time zone. something like this
TimeSpan timeSpan = DateTime.Now - c.dtimecre.Value;
double minutes = timeSpan.TotalMinutes;