Home >Java >javaTutorial >Java code example to calculate the time between two dates

Java code example to calculate the time between two dates

Y2J
Y2JOriginal
2017-04-25 14:21:031530browse

This article mainly introduces the relevant information about java calculating the time between two dates. Friends who need it can refer to it

java calculates the time between two dates

There is a field in the database of datetime type, and I want to calculate how many days, hours, and minutes have passed between two dates.

The idea is to convert time into milliseconds (the time difference from midnight on January 1, 1970 UTC (measured in milliseconds)). Then use the addition and subtraction of milliseconds to calculate.

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);//天数
    long hours=((nowTime-oldTime)%(1000*60*60*24))/(1000*60*60);//小时数
    long minutes=(((nowTime-oldTime)%(1000*60*60*24))%(1000*60*60))/(1000*60);//分钟数
    long seconds=((((nowTime-oldTime)%(1000*60*60*24))%(1000*60*60))%(1000*60))/1000;//秒数
    return days+"天"+hours+"小时"+minutes+"分钟"+seconds+"秒";
  }

The above is the detailed content of Java code example to calculate the time between two dates. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn