Home > Java > javaTutorial > body text

How to calculate the date between two dates in java

怪我咯
Release: 2017-04-07 10:28:33
Original
1898 people have browsed it

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.

is calculated 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+"秒";
  }
Copy after login


The above is the detailed content of How to calculate the date between two dates in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template