Posted In: Date, Java Core

Calculate number of days between two Java date instances

Calculate difference between two Java date instances

Techniques used

1. Using java.util.Date Before JDK 8

2. Using java.time.LocalDate JDK 8

3. Using JODA time org.joda.time.Days

4. Using JODA time org.joda.time.Interval

<dependency>
  <groupId>joda-time</groupId>
  <artifactId>joda-time</artifactId>
  <version>2.9.9</version>
</dependency>
package com.example.java.core;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Period;
import java.util.Date;

import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.Interval;

public class DateCompare {

	private void compare() throws Exception {
		// current date1
		Date date1 = new SimpleDateFormat("yyyy-MM-dd").parse("2017-08-13");

		// date before 11 days
		Date date2 = new SimpleDateFormat("yyyy-MM-dd").parse("2017-08-02");

		// current LocalDate
		LocalDate localDate1 = LocalDate.of(2017, 8, 13);

		// LocalDate before 11 days
		LocalDate localDate2 = LocalDate.of(2017, 8, 02);

		// JODA Datetime
		DateTime dateTime1 = new DateTime(date1);
		DateTime dateTime2 = new DateTime(date2);

		// Before JDK 8
		System.out.println(
		        (date1.getTime() - date2.getTime()) / (1000 * 60 * 60 * 24));

		// JDK 8
		System.out.println((Period.between(localDate2, localDate1)).getDays());

		// JODATIME Interval
		Interval interval = new Interval(date2.getTime(), date1.getTime());
		System.out.println(
		        (interval.toDuration().getMillis()) / (1000 * 60 * 60 * 24));

		// JODATIME Days
		System.out.println(Days.daysBetween(dateTime2, dateTime1).getDays());

	}

	public static void main(String[] args) throws Exception {
		new DateCompare().compare();
	}

}

by , on August 23rd, 2017

  • Categories