How do I get the time difference between two DateTime objects using C#?

前端 未结 9 2221
臣服心动
臣服心动 2020-11-27 11:38

How do I get the time difference between two DateTime objects using C#?

9条回答
  •  伪装坚强ぢ
    2020-11-27 11:42

    You want the TimeSpan struct:

    TimeSpan diff = dateTime1 - dateTime2;
    

    A TimeSpan object represents a time interval (duration of time or elapsed time) that is measured as a positive or negative number of days, hours, minutes, seconds, and fractions of a second. The TimeSpan structure can also be used to represent the time of day, but only if the time is unrelated to a particular date.

    There are various methods for getting the days, hours, minutes, seconds and milliseconds back from this structure.

    If you are just interested in the difference then:

    TimeSpan diff = Math.Abs(dateTime1 - dateTime2);
    

    will give you the positive difference between the times regardless of the order.

    If you have just got the time component but the times could be split by midnight then you need to add 24 hours to the span to get the actual difference:

    TimeSpan diff = dateTime1 - dateTime2;
    if (diff < 0)
    {
        diff = diff + TimeSpan.FromDays(1);
    }
    

提交回复
热议问题