Java如何计算两个日期之间的天数差异?
在下面的示例中,我们将计算两个日期之间的差异。首先,我们需要将日期转换为以毫秒为单位的相应值,然后进行数学计算,以便获得天,小时,分钟等之间的差异。
例如,要获取日差,我们将需要将毫秒差除以(24*60*60*1000)。
package org.nhooo.example.util; import java.util.Calendar; public class DateDifferenceExample { public static void main(String[] args) { //创建两个日历实例 Calendar cal1 = Calendar.getInstance(); Calendar cal2 = Calendar.getInstance(); //设置两个日历实例的日期 cal1.set(2006, Calendar.DECEMBER, 30); cal2.set(2007, Calendar.MAY, 3); //获取表示的日期(以毫秒为单位) long millis1 = cal1.getTimeInMillis(); long millis2 = cal2.getTimeInMillis(); //计算毫秒差 long diff = millis2 - millis1; //计算差异(以秒为单位) long diffSeconds = diff / 1000; //以分钟为单位计算差异 long diffMinutes = diff / (60 * 1000); //计算小时差 long diffHours = diff / (60 * 60 * 1000); //计算天数差异 long diffDays = diff / (24 * 60 * 60 * 1000); System.out.println("In milliseconds: " + diff + " milliseconds."); System.out.println("In seconds: " + diffSeconds + " seconds."); System.out.println("In minutes: " + diffMinutes + " minutes."); System.out.println("In hours: " + diffHours + " hours."); System.out.println("In days: " + diffDays + " days."); } }
结果如下:
In milliseconds: 10713600000 milliseconds. In seconds: 10713600 seconds. In minutes: 178560 minutes. In hours: 2976 hours. In days: 124 days.
获取两个日期之间的天数的更好方法是使用JodaTimeAPI。在下面的示例中,您可以看到如何使用JodaTime计算日期差:如何获取JodaTime中两个日期之间的天数?