This method calculates how many days are between two dates. - Java java.util

Java examples for java.util:Day

Description

This method calculates how many days are between two dates.

Demo Code


//package com.java2s;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class Main {
    public static void main(String[] argv) throws Exception {
        Date date1 = new Date();
        Date date2 = new Date();
        System.out.println(getDaysBetween(date1, date2));
    }//w  ww.  ja  v a2  s. com

    /**
     * This method calculates how many days are between two dates.
     *
     * @param date1
     * @param date2
     * @return the number of days between these two dates, ignoring the hour, minute, seconds and milliseconds.
     */
    public static int getDaysBetween(Date date1, Date date2) {
        Date normalizedDate1 = normalize(date1);
        Date normalizedDate2 = normalize(date2);

        long diffInMiliseconds = normalizedDate2.getTime()
                - normalizedDate1.getTime();

        return (int) TimeUnit.DAYS.convert(diffInMiliseconds,
                TimeUnit.MILLISECONDS);
    }

    /**
     * This method normalizes date by removing all information abut the hour, minutes, seconds and milliseconds.
     * Only information about the day, month and year are left.
     *
     * @param date
     * @return
     */
    public static Date normalize(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 1);
        return calendar.getTime();
    }
}

Related Tutorials