Java 两个日期间的天数计算
在Java中计算两个日期间的天数,大致有2种方法:一是使用原生JDK进行计算,在JDK8中提供了更为直接和完善的方法;二是使用第三方库。
1、使用原生的JDK
- private static long daysBetween(Date one, Date two) {
- long difference = (one.getTime()-two.getTime())/86400000;
- return Math.abs(difference);
- }
private static long daysBetween(Date one, Date two) {
long difference = (one.getTime()-two.getTime())/86400000;
return Math.abs(difference);
}
这种方式由于计算简单,为广大开发人员所采用。
注意:由于转换成毫秒数计算,如果要获得较为准确的结果,应将日期规整,即将日期的时分秒设置为0:00点整点,避免2日期时间(时分秒)的差异造成计算偏差。
参考代码:
- 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();
- }
- }
- }
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)
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 http://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 两个日期间的天数计算的更多相关文章
- Oracle计算两天两个日期间相差的天数
Oracle计算两天两个日期间相差的天数: select to_date('19930411','yyyymmdd')-to_date('19890507','yyyymmdd') from dual ...
- MySql获取两个日期间的时间差
[1]MySql 语言获取两个日期间的时间差 DATEDIFF 函数可以获得两个日期之间的时间差.但是,这个函数得出的结果是天数. 需要直接获取秒数可使用TIMESTAMPDIFF函数.应用示例如下: ...
- [Xcode 实际操作]九、实用进阶-(4)计算两个日期间的差值
目录:[Swift]Xcode实际操作 本文将演示如何计算两个日期之间的差值. 在项目导航区,打开视图控制器的代码文件[ViewController.swift] import UIKit class ...
- Java实现 蓝桥杯 算法训练 天数计算
试题 算法训练 天数计算 问题描述 编写函数求某年某月某日(**** ** **)是这一年的第几天 .提示:要考虑闰年,闰年的2月是29天(闰年的条件:是4的倍数但不是100的倍数,或者是400的倍数 ...
- java 计算两个日期间的所有日期
public static void main(String[] args) { Calendar start = Calendar.getInstance(); start.set(2014, 6, ...
- [java]察看两个日期间差多少秒/小时/天
Java 中Date类getTime()的方法返回从1970-1-1以来的毫秒数,这是下面函数运行的基础. package com.example.demo; import java.text.Par ...
- java日期间相隔年月日计算
/** * 获取date1相距date2多少天, date2>date1 * @param date1 * @param date2 * @return ...
- python 计算两个日期间的小时数
#!/usr/bin/env python #encoding: utf-8 import datetime def dateDiffInHours(t1, t2): td = t2 - t1 ret ...
- python获取两个日期间的工作日
import datetime # 计算两个日期之间的工作日数,非天数. class workDays(): def __init__(self, start_date, end_date, days ...
随机推荐
- Fiddler 502问题
使用Fiddler的时候遇到下面这个问题:在地址栏想打开个一般处理程序,出现连接本机失败的提示,如下图: 而这在我没打开Fiddler的时候是显示正常的. 查看Fiddler,在嗅探 -> 第二 ...
- linux-统计文本中符合条件的内容
1, 单个条件匹配, cat results.log | grep 'status=402' 2, 多个条件匹配 1), 2个条件都要满足 cat results.log | grep "s ...
- Koa2实用入门
koa2已发布了一段时间,可以考虑入手,参见Node.js最新Web技术栈(2016年4月) 本文主要是koa 2的文档解读和runkoa介绍,让大家对koa 2有一个更简单直接的理解 一.依赖Nod ...
- 布局管理器之CardLayout(卡片布局管理器)
对于选项卡这个概念大家可能不会陌生,就是在一个窗口中可以切换显示多页不同的内容,但同一时间只能是其中的某一页可见的,这样的一个个的页面就是选项卡. CardLayout就是类似的这样一个布局管理器,它 ...
- ASP.NET 多环境下配置文件web.config的灵活配置---转
注意:本功能在.Net Core中已经不可用,暂时需手动修改web.config中的信息,或者将其设置在appsettings.XXX.json中,然后再使用web.config中的环境变量来制定使用 ...
- Java的commons包的简介
Jakarta Commons是Jakarta的一个子项目,目的是创建和维护独立于其他框架和产品的程序包(packages).Jakarta Commons项目源于重用,其中的程序包必须确保能够重用. ...
- lucene源码分析(3)facet实例
简单的facet实例 public class SimpleFacetsExample { private final Directory indexDir = new RAMDirectory(); ...
- ruby实现下订单后给客户发送手机序列号
还有半个小时下班,写点今天做的功能,打发打发时间. 两个类,订单类和序列号类. 订单类 class GroupOrder include Mongoid::Document include Mongo ...
- CUBA China 最新进展
各位关注CUBA平台的朋友,你们好! 距上次发布动态我们又沉默了大概两个月时间,这期间我们一直在翻译CUBA平台的文档.CUBA平台的开发文档相当丰富,所以这需要耗费较多的时间,至少比我们预想的时间要 ...
- Node.js链式回调
由于异步的关系,代码的书写顺序可能和执行顺序并不一样,可能想先执行A再执行B,但由于异步可能B要先于A执行.例如在OC中使用AFnetworking请求数据然后刷新页面,由于网络请求是用block实现 ...