Number of days between Java two dates calculation __java

Source: Internet
Author: User
Tags abs arithmetic date1 dateformat getdate parse string java se

In Java, there are roughly 2 ways to calculate the number of days in a two-day period: first, using a native JDK for computing, providing a more direct and sophisticated approach in JDK8, and using a third-party library. 1, the use of native JDK

    private static long Daysbetween (date one, date two) {
        Long difference =  (One.gettime ()-two.gettime ())/86400000; return
        math.abs (difference);
    }
This method is used by developers for its simple calculation.

Note: As a result of the conversion to a millisecond calculation, if you want to obtain more accurate results, the date should be structured, the time of the day is set to 0:00 points, to avoid the 2nd period (time and minutes) of the difference caused by the calculation deviation.

Reference code:

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);
		Structured Method 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);
		Structured Method 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 ();
 }
	}
	
}

Regular Method 1 can not eliminate the effect of millisecond number, the result is 1 days, structured Method 1 can better eliminate the effect of time on the calculation of days.

Therefore, when calculating the difference between 2 dates, if you do not want to calculate the time difference, only calculate the number of days, you must first of the 2 dates to the regular processing, and then to calculate, otherwise the results may have greater error. 2. Use of third party library

Use a larger class library for Jodo-time.

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

Reference:

Calculate difference between two dates in Java If you are are not running on Java 8, then there are two ways to calculate the difference between the two dates into Java in either by using standard JDK classes e.g. Java.util.Date and Java.util.Calendar or by using the Joda-time library. Unfortunately, Java ' old Date and Calendar API are buggy and not intuitive, then many of us by default use Joda to all Date and time arithmetic. In this example, you'll learn how about  the number of days between the today and any date entered by a user using Jo DA, as, as without using any third the party library. When I-i-problem, I thought what ' s a big deal about finding the difference between? If you can convert Date to milliseconds then finding a number of days, months or years are-just a matter of simple Arithme TIC, but I was wrong. I wasn't 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 the Java without using third party library unless you have time to develop your the library like own, Joda which t Akes things into consideration. Thankfully, you don ' t need to worry because Java 8 got lucky time. There is a new Date and time API which has corrected previous mistakes and turns out to being real gem. If you are 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.between two dates in JavaSince Java.util.Date class implements comparable interface it ' easy to figure out whether a Date come before or after Ano Ther date, or whether two dates are equal to all other as shown where but when it comes to finding Een two dates? We don ' t have a simple to like Daysbetween (Date1, date2) in JDK Library. Unfortunately, this is a quite common requirement, as your may need to find days between today and your next birthday, or H ow many days to your next insurance premium from today, or simply the many days between the last two the world cricket. In fact, calculating date and time difference are the most common date arithmetic in java.in This article, we'll have a two Ways to solve this problem, the a using JDK, without using any third party library and second by using the Joda-time Li Brary.How do I find the difference between two dates in Java?Though all isn't lost, can quickly write a simple routine to find the difference between two dates into terms of days I N Java. How? By converting a date to milliseconds. Once you have milliseconds, can just subtract them and then again divide by86400000 (milliseconds per day). This is way you'll get exactly how to many days between two dates in Java. How would you do millisecond from a date in Java? By using GetTime () method of Java.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 would work 99% of the time, but just like any quick and dirty solution, it won't be handle any special cases. Time Or timezone, leap years, or day light saving time. It'll fail on summer boundaries when day light changes occur.

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


BTW, if you have are using JDK 8 then you and use Java.time.Period class to calculate the difference between the two dates in Java. This is a example of calculating the date and time difference in Java 8, it's super easy and don't error prone like Earlie R API. There is another class called, Java.time.Duration, which are 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 the using joda-time, we need to use a class called Localdate to represent your.  It is similar to Localdate class of Java 8, or should I say localdate be inspired by this class. This class knows about the weirdness we just talked about, e.g. some timezones don ' t have, "start at midnight." 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:

public static int Daysbetweenusingjoda (date d1, date D2) {return
    Days.daysbetween (
           new Localdate ()) , 
           new Localdate (D2.gettime ())). GetDays ();
 }

You can so Days.daysbetween () method accepts a localdate and its's very easy to convert an instance of Java.util.Dat E 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 in Joda-convert, but this isn't required at Run-time the magic of S. You can download Joda-time-2.5.jarEither from Maven, or directly from Http://www.joda.org/joda-time/website. If you are are using Maven then you can also add the following dependency into your file:

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

If you are download JAR file then make sure your add Joda-time-2.5.jar in your Java program's classpath and you are done. If you are are not sure, then, this tutorial.

difference between two dates inThis is my 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 U
 Sing Joda-time library. * * @author WINDOWS 8/public class Datediffexample {private static final dateformat df = new Simpledate
    
    Format ("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 a = Reader.nextline ();
      
      String second = Reader.nextline ();
      Date one = GetDate (a);
      
      Date two = GetDate (second); Quick and dirty way, work but not in all COnditions//can convert date into milliseconds then subtract//them and again convert it to days l
      Ong numberofdays = Daysbetween (one, two);
          
      
      System.out.printf ("Number of days between date%s and%s are:%d%n", second, numberofdays); A better way to calculate difference between two dates in Java/are by using Jodatime library A
      s shown below int differencebetweendates = Daysbetweenusingjoda (one, two); System.out.printf ("Difference betweeen two dates%s and%s is:%d%n", I, second, differencebetweendate
      
      
      s);
    Reader.close (); } * * Simple way to parse String to date in Java */private static date GetDate (String date) throw
    S parseexception{return df.parse (date); }/* Java method to calculate difference between two dates in Java * without using the any third par
     Ty 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-need to convert java.util.Date to Localdate * in Jodatime. */public static int Daysbetweenusingjoda (date d1, date D2) {return Days.daysbetween (new Loca
    Ldate (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
You can have a number of days between two dates are correct and output of both we own method and Joda-time are same.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.