1. 程式人生 > >Java 兩個日期間的天數計算

Java 兩個日期間的天數計算

If you are not running on Java 8, then there are two ways to calculate the difference between two dates in Java in days, either by using standard JDK classes e.g.java.util.Date andjava.util.Calendar or by using the joda-time library. Unfortunately, Java's old Date and Calendar API is buggy and not intuitive, so many of us by default use Joda for all date and time arithmetic. In this example, you will learn how to find  the number of days between today and any date entered by a user using Joda, as well as without using any third party library. When I first time face this problem, I thought what's a big deal about finding the difference between dates? If you can
convert Date to milliseconds
then finding a number of days, months or years are just a matter of simple arithmetic, but I was WRONG. I was not thinking about real world date and time nuisance like leap seconds, leap years, and daylight saving time.It's very difficult to accurately calculate the difference between two dates in Java without using third party library unless you have time to develop your own library like Joda, which diligently takes these things into consideration. Thankfully, you don't need to worry because Java 8 got lucky third time.There is a new Date and Time API which has corrected previous mistakes and turns out to be a real gem. If you are keen to learn Java 8, not just this API, I suggest you grab a copy of Java 8 in Action, one of the better books to learn new features of Java 8 in quick time.

How to find number of days between two dates in Java

Since java.util.Date class implementsComparable interface it's easy to figure out whether a date come before or after another date, or whether two dates are equal to each other as shownhere, but when it comes tofinding out how many days between two dates? we don't have a simple method likedaysBetween(date1, date2)
in JDK library. Unfortunately, this is a quite common requirement, as you may need to find days between today and your next birthday, or how many days to your next insurance premium from today, or simply how many days between last two cricket world cups. In fact, calculating date and time difference is the most common date arithmetic in Java.In this article, we will see two ways to solve this problem, first by using JDK, without using any third party library and second by using the joda-time library.

How to find the difference between two dates in Java?

Though all is not lost, you can quickly write a simple routine to find the difference between two dates in terms of days in Java. How? By converting a date to milliseconds. Once you have milliseconds, you can just subtract them and then again divide them by86400000 (milliseconds per day). This way you will get exactly how many days between two dates in Java. How will you get millisecond from a date in Java? by usinggetTime() method ofjava.util.Date class, as shown below :
 private static long daysBetween(Date one, Date two) {
        long difference =  (one.getTime()-two.getTime())/86400000;
        return Math.abs(difference);
    }


This will work 99% of the time, but just like any quick and dirty solution, it will not handle any special cases e.g. time or timezone, leap years, or day light saving time. It will fail on summer boundaries when day light changes occur.

A better solution is to use a tried and tested date and time library like Joda-Time, which handles those tricky scenarios much better. Alternatively, you can also use newjava.time classes from Java 8, which are heavily influenced from the joda-time library. SeeJava SE 8 for Really Impatient by Cay S. Horstmann for more details.


BTW, if you are using JDK 8 then you and use java.time.Period class to calculate the difference between two dates in Java. Here is an example ofcalculating the date and time difference in Java 8, it's super easy and not error prone like earlier API. There is another class called,java.time.Duration, which is good to calculate a time difference between two instant.

How to calculate days between two dates using joda-time in Java?

In order to solve this problem using joda-time, we need to use a class called LocalDate to represent your dates. It is similar to LocalDate class of Java 8, or should I say LocalDate is inspired by this class.  This class knows about the weirdness we just talked about, e.g. some timezones don't have days that start at midnight. You can calculate difference between two dates in joda by using static utility class Days, which has method daysBetween() to return the number of days between two given dates as shown in the following example :

 public static int daysBetweenUsingJoda(Date d1, Date d2){
    return Days.daysBetween(
           new LocalDate(d1.getTime()), 
           new LocalDate(d2.getTime())).getDays();
 }

You can see that Days.daysBetween() method accepts a LocalDate and its's very easy to convert an instance of java.util.Date to org.joda.time.LocalDate class, just pass a number of milliseconds to it.


Dependency for Joda Time library
Joda-Time requires Java SE 5 or later and has no dependencies. There is a compile-time dependency on Joda-Convert, but this is not required at run-time thanks to the magic of annotations. You can downloadjoda-time-2.5.jar either from Maven central or directly from  website. If you are using Maven then you can also add the following dependency into your pom.xml file :

<dependency>
  <groupId>joda-time</groupId>
  <artifactId>joda-time</artifactId>
  <version>2.5</version>
</dependency>

If you download JAR file then make sure you add joda-time-2.5.jar in your Java program's classpath and you are done.  If you are not sure how to do that, see thistutorial.

Difference between two dates in number of Days

Here is our full Java program to find out how many days between two dates in Java using standard JDK classes and by using open source Joda Time library. I have name aptly named our program "date diff", as its calculating difference between dates.

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

import org.joda.time.Days;
import org.joda.time.LocalDate;

/**
 * Java Program to find number of days between two dates in Java.
 * This program calculate difference between two dates in days using two ways
 * without using third party library and by using joda-time library.
 *
 * @author WINDOWS 8
 */

public class DateDiffExample {   
    
    private static final DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
    
    public static void main(String args[]) throws ParseException{
        
      System.out.println("Please enter two dates in format yyyy/MM/dd to compare");
      Scanner reader = new Scanner(System.in);
      
      String first = reader.nextLine();
      String second = reader.nextLine();
      
      Date one = getDate(first);
      Date two = getDate(second);
      
      // quick and dirty way, work but not in all conditions
      // you can convert date into milliseconds then subtract
      // them and again convert it to days
      long numberOfDays = daysBetween(one, two);
      System.out.printf("Number of days between date %s and %s is : %d %n",
              first, second, numberOfDays);
          
      
      // a better way to calculate difference between two dates in Java
      // is by using JodaTime library as shown below
      int differenceBetweenDates = daysBetweenUsingJoda(one, two);
      System.out.printf("difference betweeen two dates %s and %s is : %d %n",
              first, second, differenceBetweenDates);
      
      
      reader.close();
    }
    
    /*
     * Simple way to parse String to date in Java
     */
    private static Date getDate(String date) throws ParseException{
        return df.parse(date);
    }
    
    
    /*
     * Java Method to calculate difference between two dates in Java
     * without using any third party library.
     */
    private static long daysBetween(Date one, Date two) {
        long difference =  (one.getTime()-two.getTime())/86400000;
        return Math.abs(difference);
    }
    
   
    /*
     * Java Method to find number of days between two dates
     * in Java using JodaTime library. To find difference 
     * we first need to convert java.util.Date to LocalDate
     * in JodaTime.
     */
    public static int daysBetweenUsingJoda(Date d1, Date d2){
        return Days.daysBetween(
                new LocalDate(d1.getTime()), 
                new LocalDate(d2.getTime())).getDays();
    }
}

Output:
Please enter two dates in format yyyy/MM/dd to compare
2014/11/23
2014/11/25
Number of days between date 2014/11/23 and 2014/11/25 is : 2 
difference between two dates 2014/11/23 and 2014/11/25 is : 2 
You can see that number of days between two dates are correct and output of both our own method and joda-time is same.

相關推薦

Java 期間天數計算

If you are not running on Java 8, then there are two ways to calculate the difference between two dates in Java in days, either by using standard JDK class

java實現計算期間間隔天數

 SimpleDateFormat  df=new  SimpleDateFormat( "yyyy-MM-dd");  Date d1,d2;  long HM;  try {   d1= df.parse(text1);   //讀取文字框中輸入的字串,並將其轉化為日期

java獲取當前日期前一週、前一個月、當年的時間、期間的間隔天數

獲取以當前日期為結束日期的一週內的時間: String paramStartDate = ""; String paramEndDate = ""; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); D

Java計算期間的年,月,之差

由於在開發中需要計算車的使用年限,我當時使用的是以下方案並記錄下來,希望能給有需要計算日期差的朋友有所幫助。當然,中間的計算邏輯根據不同要求來計算。 有錯的地方請留言告知 /** * 計算使用年限 * enrollDate :註冊日期 *

[Java] 獲取期間的所有日期

nbsp imp urn getdate for simple java mon turn def GetDates(String startDate, String endDate){   Date d1 = new SimpleDateFormat("yyyyMMdd"

JAVA 獲取期間的所有日期

public static List<String> getDates(Date startDate, Date endDate){          SimpleDateFormat sdf = new Simple

C/C++ 結構體(期間天數)

題目描述 求兩個日期d1,d2之間相差的天數d2-d1。 輸入  輸入資料有若干組。每組資料一行,有六個整數,表示兩個日期d1,d2,格式為:年月日。 輸出  對於每一組資料,輸出兩個日期d1,d2之間相差的天數, 格式參照樣例輸出。 樣例輸入 2000 1 1

LocalDate計算期間距離

1、LocalDate提供了until()方法,計算了兩個日期之間的年、月和日的週期 例如: from {@code 2017-08-28} to {@code 2018-09-30} is "1 year, 1 months and 2 days" 示例程式碼: Lo

JavaScript如何計算期間的時間差

<scripttype="text/javascript">/* * 獲得時間差,時間格式為 年-月-日 小時:分鐘:秒 或者 年/月/日 小時:分鐘:秒 * 其中,年月日為全格式,例如 : 2010-10-12 01:00:00 * 返回精度為:秒,分,

SQL Server 獲取期間的日期

() serve server cts where sele sel lar obj declare @start datetime declare @end datetime set @start = ‘2018-01-25‘ set @end = ‘201

獲取期間的所有日期

between func UNC urn pan fda push amp nth /** ***獲取兩個日期間的所有日期 ***默認start<end **/ getBetweenDateStr(‘2017-07-08‘,‘20

MySql獲取期間的時間差

【1】MySql 語言獲取兩個日期間的時間差 DATEDIFF 函式可以獲得兩個日期之間的時間差。但是,這個函式得出的結果是天數。 需要直接獲取秒數可使用TIMESTAMPDIFF函式。應用示例如下: 1 SELECT TIMEDIFF('2018-12-19 12:01:01

sqlserver 算期間的月份數

create FUNCTION f_GetRentalMonths_double(@StartDate DATETIME ,@EndDate DATE) RETURNS DECIMAL(10,4) AS BEGIN DECLARE @DiffMonths DECIMAL(10

sqlserver中返回期間相差幾年零幾月零幾天,DATEDIFF通常不準確

--實際差12月+1天 select DATEDIFF(M,'2013-08-31','2014-09-01') as [13] ,DATEDIFF(D,'2013-08-31','2014-09-01') AS [366] ,DATEDIFF(D,'2013-08-31

python獲取期間的工作日

結束 def 一周內 列表 sta 元素 獲取 排除 結果 import datetime # 計算兩個日期之間的工作日數,非天數. class workDays(): def __init__(self, start_date, end_date, da

java實現計算日期相差天數

要求:計算1999年1月1日和2018年11月3日相差多少天 思路: 1、每年的天數累加,需判斷閏年、平年 2、每月的天數累加,不同月份天數不同,平年和閏年,2月份的天數也不同 3、將日期天數累加 (因為計算的是相差的天數,所以這個天數需要減1天,所以這裡加2就可以了) packag

java 計算生日 剩餘天數日期間隔天數

 public Object decorate(Object columnValue, PageContext pageContext, MediaTypeEnum media) throws DecoratorException    {        Object obj

java 計算日期之間天數

 import java.text.ParseException; import java.text.SimpleDateFormat; /** * @author JavaAlpha * @

php 計算日期相差天數

class end rto date 日期相差 天數 day sharp echo php 計算兩個日期相差天數 <?php $startdate=strtotime("2013-3-09"); $enddate=strtotime("2013-

MYSQL如何計算日期間隔天數

如何透過MYSQL自帶函式計算給定的兩個日期的間隔天數 有兩個途徑可獲得 1、利用TO_DAYS函式 select to_days(now()) - to_days('20120512') 2、利用DATEDIFF函式 select datediff(now(),'201205