java calculates the time between two dates

  • 2020-06-15 09:09:17
  • OfStack

java calculates the time between two dates

One of the fields in the database is of type datetime and you want to calculate how many days, hours and minutes have passed between two dates.

The idea is to convert time into milliseconds (measured in milliseconds) between midnight UTC on January 1, 1970. And then you add and subtract in milliseconds.

The calculation is as follows:


public static String getDays(Date date){
    Calendar cal=Calendar.getInstance();
    cal.setTime(date);
    long oldTime=cal.getTimeInMillis();
    long nowTime=System.currentTimeMillis();
    long days=(nowTime-oldTime)/(1000*60*60*24);// Number of days 
    long hours=((nowTime-oldTime)%(1000*60*60*24))/(1000*60*60);// Number of hours 
    long minutes=(((nowTime-oldTime)%(1000*60*60*24))%(1000*60*60))/(1000*60);// minutes 
    long seconds=((((nowTime-oldTime)%(1000*60*60*24))%(1000*60*60))%(1000*60))/1000;// Number of seconds 
    return days+" day "+hours+" hours "+minutes+" minutes "+seconds+" seconds ";
  }

Thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: