Search code examples
c#.net-coretimedatetimeoffsetdate-difference

How to get only the time difference, ignoring the date difference, between two DateTimeOffset in C#?


i am using c# and I need to get the difference between two DateTimeOffset() ignoring the year, month and day witch mean get the difference between the hour, minutes and the seconds. lets say this is my start date "startDate": "2021-08-28T13:30:00+00:00" and this my end date "endDate": "2021-08-30T13:45:00+00:00" for this example I want the result to be 15.


Solution

  • It sounds like you're looking for DateTimeOffset.TimeOfDay:

    The time interval of the current date that has elapsed since midnight.

    var dto1 = DateTimeOffset.Parse("2021-08-28T13:30:00+00:00");
    var dto2 = DateTimeOffset.Parse("2021-08-30T13:45:00+00:00");
    var diff = dto2.TimeOfDay.Subtract(dto1.TimeOfDay);
    

    Convert the resulting TimeSpan to whatever units you want.