Java Date Difference diff(Date date1, Date date2)

Here you can find the source of diff(Date date1, Date date2)

Description

diff

License

Open Source License

Declaration

public static int diff(Date date1, Date date2) throws Exception 

Method Source Code

//package com.java2s;

import java.text.SimpleDateFormat;

import java.util.Date;

public class Main {
    public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";

    public static int diff(Date date1, Date date2) throws Exception {
        long day = 24L * 60L * 60L * 1000L;
        String str1 = date2Str(date1, "yyyy-MM-dd");
        date1 = str2Date(str1, "yyyy-MM-dd");
        String str2 = date2Str(date2, "yyyy-MM-dd");
        date2 = str2Date(str2, "yyyy-MM-dd");

        return (int) (((date2.getTime() - date1.getTime()) / day));
        //return (int) Math.ceil((((date2.getTime() - date1.getTime()) / (24 * 60 * 60 * 1000d))));
    }//ww w .  j a  v  a2 s. c  om

    public static int diff(Date date) throws Exception {
        return diff(new Date(), date);
    }

    public static String date2Str(Date date, String pattern) {
        if (null == date) {
            return null;
        }
        if (null == pattern) {
            pattern = DEFAULT_DATE_FORMAT;
        }
        SimpleDateFormat format = new SimpleDateFormat();
        format.applyPattern(pattern);
        return format.format(date);
    }

    public static Date str2Date(String dateStr, String pattern)
            throws Exception {
        if (null == dateStr) {
            return null;
        }
        if (null == pattern) {
            pattern = DEFAULT_DATE_FORMAT;
        }
        SimpleDateFormat format = new SimpleDateFormat();
        format.applyPattern(pattern);
        return format.parse(dateStr);
    }
}

Related

  1. dayDiff(Date first, Date second)
  2. dayDiffByStartOfDay(Date a, Date b)
  3. daysDiff(Date d1, Date d2)
  4. diff(Date d1, Date d2)
  5. diff(Date date1, Date date2)
  6. diff(Date endDate, Date startDate)
  7. diff(Date sDate, Date fDate)
  8. diff(Date subtrahend, Date minuend, long diffField)
  9. diff(int type, Date date1, Date date2)