Check difference in seconds between two times

前端 未结 4 2016
挽巷
挽巷 2020-12-07 19:36

Hi all I am currently working on a project where when a certain event happens details about the event including the time that the event occurred is added into a list array.

相关标签:
4条回答
  • 2020-12-07 20:03

    I use this to avoid negative interval.

    var seconds = (date1< date2)? (date2- date1).TotalSeconds: (date1 - date2).TotalSeconds;
    
    0 讨论(0)
  • 2020-12-07 20:09

    Assuming dateTime1 and dateTime2 are DateTime values:

    var diffInSeconds = (dateTime1 - dateTime2).TotalSeconds;
    

    In your case, you 'd use DateTime.Now as one of the values and the time in the list as the other. Be careful of the order, as the result can be negative if dateTime1 is earlier than dateTime2.

    0 讨论(0)
  • 2020-12-07 20:10

    This version always returns the number of seconds difference as a positive number (same result as @freedeveloper's solution):

    var seconds = System.Math.Abs((date1 - date2).TotalSeconds);
    
    0 讨论(0)
  • 2020-12-07 20:26

    DateTime has a Subtract method and an overloaded - operator for just such an occasion:

    DateTime now = DateTime.UtcNow;
    TimeSpan difference = now.Subtract(otherTime); // could also write `now - otherTime`
    if (difference.TotalSeconds > 5) { ... }
    
    0 讨论(0)
提交回复
热议问题