Java 两个日期间的天数计算

摘要:
在Java中计算两个日期间的天数,大致有2种方法:一是使用原生JDK进行计算,在JDK8中提供了更为直接和完善的方法;二是使用第三方库。因此,计算2个日期间的差别时,若不希望计算时间差异,只计算天数,则一定要先对2个日期进行规整处理,然后再进行计算,否则得到的结果可能会有较大的误差。

在Java中计算两个日期间的天数,大致有2种方法:一是使用原生JDK进行计算,在JDK8中提供了更为直接和完善的方法;二是使用第三方库。

1、使用原生的JDK

  1. privatestaticlongdaysBetween(Dateone,Datetwo){
  2. longdifference=(one.getTime()-two.getTime())/86400000;
  3. returnMath.abs(difference);
  4. }
    private static long daysBetween(Date one, Date two) {
        long difference =  (one.getTime()-two.getTime())/86400000;
        return Math.abs(difference);
    }

这种方式由于计算简单,为广大开发人员所采用。

注意:由于转换成毫秒数计算,如果要获得较为准确的结果,应将日期规整,即将日期的时分秒设置为0:00点整点,避免2日期时间(时分秒)的差异造成计算偏差。

参考代码:

  1. importjava.text.SimpleDateFormat;
  2. importjava.util.Date;
  3. publicclassDateTest{
  4. privateintgetTermDays2()throwsException{
  5. StringsEndDate="2018-03-01";
  6. SimpleDateFormatsdf=newSimpleDateFormat("yyyy-MM-dd");
  7. Datedate1=newDate();
  8. Datedate2=sdf.parse(sEndDate);
  9. longdays=(date2.getTime()-date1.getTime())/(24*3600*1000);
  10. longyushu=(date2.getTime()-date1.getTime())%(24*3600*1000);
  11. System.out.println("days:"+days+",yushu:"+yushu);
  12. //规整方法1
  13. date1.setHours(0);
  14. date1.setMinutes(0);
  15. date1.setSeconds(0);
  16. longdays2=(date2.getTime()-date1.getTime())/(24*3600*1000);
  17. longyushu2=(date2.getTime()-date1.getTime())%(24*3600*1000);
  18. System.out.println("days2:"+days2+",yushu2:"+yushu2);
  19. //规整方法2
  20. Stringsdate1=sdf.format(date1);
  21. date1=sdf.parse(sdate1);
  22. longdays3=(date2.getTime()-date1.getTime())/(24*3600*1000);
  23. longyushu3=(date2.getTime()-date1.getTime())%(24*3600*1000);
  24. System.out.println("days3:"+days3+",yushu3:"+yushu3);
  25. return(int)days;
  26. }
  27. publicstaticvoidmain(String[]args){
  28. DateTestdt=newDateTest();
  29. try{
  30. dt.getTermDays2();
  31. }catch(Exceptione){
  32. e.printStackTrace();
  33. }
  34. }
  35. }
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTest {
	private int getTermDays2() throws Exception{
		String sEndDate = "2018-03-01";		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date1 = new Date();
		Date date2 = sdf.parse(sEndDate);
		long days = (date2.getTime() - date1.getTime()) / (24*3600*1000);
		long yushu = (date2.getTime() - date1.getTime()) % (24*3600*1000);
		System.out.println("days:" + days + ",yushu:" + yushu);
           //规整方法1 
		date1.setHours(0);
		date1.setMinutes(0);
		date1.setSeconds(0);
		long days2 = (date2.getTime() - date1.getTime()) / (24*3600*1000);
		long yushu2 = (date2.getTime() - date1.getTime()) % (24*3600*1000);
		System.out.println("days2:" + days2 + ",yushu2:" + yushu2);
           //规整方法2 
		String sdate1 = sdf.format(date1);
		date1 = sdf.parse(sdate1);
		long days3 = (date2.getTime() - date1.getTime()) / (24*3600*1000);
		long yushu3 = (date2.getTime() - date1.getTime()) % (24*3600*1000);
		System.out.println("days3:" + days3 + ",yushu3:" + yushu3);		
		return (int)days;
	}
	public static void main(String[] args) {
		DateTest dt = new DateTest();
		try {
			dt.getTermDays2();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

规整方法1无法消除毫秒数的影响,结果差1天;规整方法1则可较好地消除时间对天数计算的影响。

因此,计算2个日期间的差别时,若不希望计算时间差异,只计算天数,则一定要先对2个日期进行规整处理,然后再进行计算,否则得到的结果可能会有较大的误差。

2、使用第三方库

使用较多的类库为jodo-time。

http://www.joda.org/joda-time/

参考:

How to Calculate Difference between two Dates in Java (In Days)
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 fromhttp://www.joda.org/joda-time/ 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 两个日期间的天数计算》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇SetFilePointer 使用Eclipse设置:背景与字体大小和xml文件中字体大小调整下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

QQ等级计算方法及图标

在线时长从去年下半年开始统计,使用腾讯QQ(包括在线,隐身,离开状态),使用腾讯TM,或是在Wince平台下用手机登录腾讯QQ,均计入在线时长。在线状态下不即时更新在线时长,每次下线后,更新本次的在线时长和等级。在线时长等级由太阳,月亮,星星三个图标标识。 在线时长积满20小时,即可获得一颗星星,获得第二颗星星需要再累积30小时,获得第三颗星星需要再累积4...

计算请假天数JavaScript方法

前言 最近,有这么个需求,给用户做个请假审批系统,要输入请假开始时间和结束时间,同时计算出请假天数,如果年假数量不够提示不能提交,如果年假数量够的话,就走审批工作流,审批通过以后,自动在年假上减去这个请假天数。 审批流程很简单,就是找自己的经理审批就好了,在SharePoint里创建一个简单的workflow就可以实现。但是请假天数着实花了点时间,用Jav...

LocalDate计算两个日期相差天数

importorg.apache.commons.lang.StringUtils; importjava.time.LocalDate; importjava.time.ZoneId; importjava.time.format.DateTimeFormatter; importjava.time.temporal.ChronoUnit; impo...

Javascript 计算请假天数

转载请注明本文地址:https://www.cnblogs.com/qiaoge0923/p/10219155.html  计算请假天数,笼统来说就是计算两个日期的差值。对于JS来说,两个时间直接相减,得到的是这两个时间差的毫秒数。 先上代码后贴图。 1.测试数据 后文中用到的测试数据如下: var dateStart = '2018-12-01 04...

iOS 计算两个日期之间的天数问题

1 //获取当前时间若干年、月、日之后的时间 2 + (NSDate *)dateWithFromDate:(NSDate *)date years:(NSInteger)years months:(NSInteger)months days:(NSInteger)days{ 3 NSDate *latterDate; 4 if(dat...

人力资本层-考勤评估案例

员工信息表 计算员工出勤率: 解读:出勤率(病假不计入出勤):出勤天数÷规定的月工作日×100% =B2/NETWORKDAYS(DATE(2019,11,1),DATE(2019,11,30)) NETWORKDAYS函数 功能:返回两个日期之间的完整工作日数 语法结构: NETWORKDAYS(开始日期,结束日期,[非工作日日期]) 计算加班强度...