Java Day Between getDifference(Date d1, Date d2)

Here you can find the source of getDifference(Date d1, Date d2)

Description

Get date difference => d1 - d2.

License

Open Source License

Declaration

public static String getDifference(Date d1, Date d2) 

Method Source Code

//package com.java2s;
/***************************************************************************
 * Copyright (c) 2006 Eike Stepper, Fuggerstr. 39, 10777 Berlin, Germany.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * //  ww  w  . jav  a2  s . co  m
 * Contributors:
 *    Eike Stepper - initial API and implementation
 **************************************************************************/

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class Main {
    /**
     * Get date difference => d1 - d2.
     */
    public static String getDifference(Date d1, Date d2) {
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(d2);
        int year2 = calendar.get(Calendar.YEAR);
        int day2 = calendar.get(Calendar.DAY_OF_YEAR);
        int hour2 = calendar.get(Calendar.HOUR_OF_DAY);
        int min2 = calendar.get(Calendar.MINUTE);

        calendar.setTime(d1);
        int year1 = calendar.get(Calendar.YEAR);
        int day1 = calendar.get(Calendar.DAY_OF_YEAR);
        int hour1 = calendar.get(Calendar.HOUR_OF_DAY);
        int min1 = calendar.get(Calendar.MINUTE);

        int leftDays = (day1 - day2) + (year1 - year2) * 365;
        int leftHours = hour1 - hour2;
        int leftMins = min1 - min2;

        if (leftMins < 0) {
            leftMins += 60;
            --leftHours;
        }
        if (leftHours < 0) {
            leftHours += 24;
            --leftDays;
        }

        String interval = "";
        if (leftDays > 0) {
            interval = leftDays + " Days";
        } else if ((leftHours > 0) && (leftDays == 0)) {
            interval = leftHours + " Hours";
        } else if ((leftMins > 0) && (leftHours == 0) && (leftDays == 0)) {
            interval = leftMins + " Minutes";
        } else {
            interval = "";
        }
        return interval;
    }
}

Related

  1. getDiffBetweenQuarter(Date latestDate, Date current)
  2. getDiffDays(Date date1, Date date2)
  3. getDiffDays(String startDate, String endDate)
  4. getDifferDays(Date d1, Date d2)
  5. getDifferDays(String date1, String date2)
  6. getDifferenceInDays(final Date startDate, final Date endDate)
  7. getDifferenceOfDays(String dateFromStr, String dateToStr, String dateFormat)
  8. getDifferencesBetweenIndicateDays( final Date minorDate, final Date majorDate)
  9. getDiffMilliSeconds(Date form, Date to)