Java Date Difference dateDiff(int category, Date date1, Date date2)

Here you can find the source of dateDiff(int category, Date date1, Date date2)

Description

date Diff

License

Apache License

Parameter

Parameter Description
category a parameter
date1 a parameter
date2 a parameter

Declaration

public static int dateDiff(int category, Date date1, Date date2) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

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

public class Main {
    public static final int YEAR = 1;
    public static final int MONTH = 2;
    public static final int DAY = 3;
    public static final int HOUR = 4;
    public static final int MINUTE = 5;
    public static final int SECOND = 6;

    /**/*from   ww w  .j av a  2 s.  com*/
     *
     *
     * @param category
     *
     * @param date1
     * @param date2
     * @return
     */
    public static int dateDiff(int category, Date date1, Date date2) {
        Calendar c1 = Calendar.getInstance();
        c1.setTime(date1);
        Calendar c2 = Calendar.getInstance();
        c2.setTime(date2);
        if (YEAR == category) {
            return Math.abs(c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR));
        } else if (MONTH == category) {
            return Math.abs((((c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR)) * 12) + c2.get(Calendar.MONTH))
                    - c1.get(Calendar.MONTH));
        } else if (DAY == category) {
            return Integer.parseInt(Long.toString((date2.getTime() - date1.getTime()) / 86400000));
        } else if (HOUR == category) {
            return Integer.parseInt(Long.toString((date2.getTime() - date1.getTime()) / 3600000));
        } else if (MINUTE == category) {
            return Integer.parseInt(Long.toString((date2.getTime() - date1.getTime()) / 60000));
        } else if (SECOND == category) {
            return Integer.parseInt(Long.toString((date2.getTime() - date1.getTime()) / 1000));
        } else {
            return -1;
        }
    }
}

Related

  1. dateDiff(Date date1, Date date2)
  2. dateDiff(Date date1, Date date2)
  3. dateDiff(Date fromDate, Date toDate)
  4. DateDiff(Date startDate, Date endDate)
  5. dateDiff(final Date date1, final Date date2)
  6. dateDiff(int interval, Date begin, Date end)
  7. dateDiff(java.util.Date a, java.util.Date b)
  8. dateDiff(String startDate, String endDate)
  9. dateDiff(String startTime, String endTime, String format)