Home > Enterprise >  calculate the difference between two UTC times in hours C#
calculate the difference between two UTC times in hours C#

Time:01-11

How do I calculate the difference between two UTC times in hours?

This is what I have tried:

// var lastSuccessfulRunTime = 2023-01-01T00:00:00Z UTC Time
int timeDifference = (DateTime.UtcNow - lastSuccessfulRunTime).Hours

if (DateTime.UtcNow - lastSuccessfulRunTime) = 9.00:00:00.7944388, timeDifference will be 0 which is not what I need.

CodePudding user response:

The Hours property returns the integer hours value of the timespace.

i.e. for an hour and a half, it would give you 1.

The TotalHours property, converts the entire timespan into the double representation.

i.e. for an hour and a half, it would give you 1.5

You want:

double timeDifference = (DateTime.UtcNow - lastSuccessfulRunTime).TotalHours

(note, your int variable type is also wrong)

This applies to all of the time-component properties on a DateTime

  • Related