Difference in time between two dates in java

前端 未结 4 1952
礼貌的吻别
礼貌的吻别 2021-01-01 10:24

I have to find the difference in time between two different date objects in java and if that time exceeds 5 sec i have to invalidate the session.

Here\'s the scenari

相关标签:
4条回答
  • 2021-01-01 10:32

    From Java-8 onwards you may use-

    ChronoUnit.DAYS.between(startDate.toInstant(), endDate.toInstant());
    

    This is a generic Enum using which, it becomes pretty simple to find difference in any Unit.

    0 讨论(0)
  • 2021-01-01 10:37
    if ((date2.getTime() - date1.getTime()) > 5000) { // getTime returns the time in milliseconds
        // invalidate
    }
    

    But the session timeout is supposed to be handled by the container, not by you.

    PS : this is easily answered by reading the javadoc : http://download.oracle.com/javase/6/docs/api/index.html

    0 讨论(0)
  • 2021-01-01 10:43
       long difference = date2.getTime() - date1.getTime();
    
        // now you have your answer in milliseconds - 
    //so divide by 1000 to get the time in seconds
    
    0 讨论(0)
  • 2021-01-01 10:53

    Building on the other answers, java.util.concurrent.TimeUnit makes it very easy to convert between milliseconds, seconds, etc...

     long differenceInSeconds = TimeUnit.MILLISECONDS.toSeconds(date2.getTime() - date1.getTime());
    
    0 讨论(0)
提交回复
热议问题