Java Date Difference getDifference(Date a, Date b)

Here you can find the source of getDifference(Date a, Date b)

Description

get Difference

License

Open Source License

Declaration

public static int getDifference(Date a, Date b) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2010 Boeing.//  ww  w  .j a va  2s . c  o  m
 * 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
 *
 * Contributors:
 *     Boeing - initial API and implementation
 *******************************************************************************/

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Main {
    public static int getDifference(Date a, Date b) {
        int tempDifference = 0;
        int difference = 0;
        Calendar earlier = Calendar.getInstance();
        Calendar later = Calendar.getInstance();

        if (a.compareTo(b) < 0) {
            earlier.setTime(a);
            later.setTime(b);
        } else {
            earlier.setTime(b);
            later.setTime(a);
        }

        while (earlier.get(Calendar.YEAR) != later.get(Calendar.YEAR)) {
            tempDifference = 365 * (later.get(Calendar.YEAR) - earlier.get(Calendar.YEAR));
            difference += tempDifference;

            earlier.add(Calendar.DAY_OF_YEAR, tempDifference);
        }

        if (earlier.get(Calendar.DAY_OF_YEAR) != later.get(Calendar.DAY_OF_YEAR)) {
            tempDifference = later.get(Calendar.DAY_OF_YEAR) - earlier.get(Calendar.DAY_OF_YEAR);
            difference += tempDifference;

            earlier.add(Calendar.DAY_OF_YEAR, tempDifference);
        }

        return difference;
    }

    public static String get(Date date) {
        if (date == null) {
            return "";
        }
        return DateFormat.getDateInstance().format(date);
    }

    public static String get(Date date, String pattern) {
        return get(date, new SimpleDateFormat(pattern));
    }

    public static String get(Date date, DateFormat dateFormat) {
        if (date == null) {
            return "";
        }
        String result = dateFormat.format(date);
        return result;
    }
}

Related

  1. getDayDiff(Date firstDate, Date secondDate)
  2. getDiff(Date from, Date to)
  3. getDiffDate(String srcDate, String format, int diff)
  4. getDiffDays(Date from, Date to)
  5. getDiffDays2(Date one, Date two)
  6. getDifference(String dateStr1, String dateStr2, char choice)
  7. getDifferenceInDays(Calendar calendar0, Calendar calendar1)
  8. getDiffMon(Date dt, int idiff)
  9. getDiffMon(Date dt, int idiff)