Android Date Interval Get secondDiff(Date date1, Date date2)

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

Description

second Diff

License

Open Source License

Declaration

public static int secondDiff(Date date1, Date date2) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.HashMap;
import java.util.Map;

public class Main {
    public static final String YMD_DASH_WITH_TIME = "yyyy-MM-dd HH:mm:ss";
    public static final long ND = 1000 * 24 * 60 * 60;
    public static final long NH = 1000 * 60 * 60;
    public static final long NM = 1000 * 60;
    private static final Map<String, DateFormat> DFS = new HashMap<String, DateFormat>();

    public static int secondDiff(Date date1, Date date2) {
        long diff = date1.getTime() - date2.getTime();
        long day = diff / ND;
        long min = diff % ND % NH / NM + day * 24 * 60;
        return (int) min;
    }//  w w  w. java2 s . c o m

    public static int secondDiff(String startTime, String endTime) {
        SimpleDateFormat sd = new SimpleDateFormat(YMD_DASH_WITH_TIME);
        long diff = 0;
        long min = 0;
        try {
            diff = sd.parse(endTime).getTime()
                    - sd.parse(startTime).getTime();
            long day = diff / ND;
            min = diff % ND % NH / NM + day * 24 * 60;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return (int) min;
    }

    /**
     * @param source
     * @param pattern
     * @return Date
     */
    public static Date parse(String source, String pattern) {
        if (source == null) {
            return null;
        }
        Date date;
        try {
            date = getFormat(pattern).parse(source);
        } catch (ParseException e) {
            return null;
        }
        return date;
    }

    public static DateFormat getFormat(String pattern) {
        DateFormat format = DFS.get(pattern);
        if (format == null) {
            format = new SimpleDateFormat(pattern);
            DFS.put(pattern, format);
        }
        return format;
    }
}

Related

  1. minutesBetween(Date dt1, Date dt2)
  2. minutesBetween(Date dt1, Date dt2)
  3. offsetMinute(Date date, int offset)
  4. offsetSecond(Date date, int offset)
  5. secondBetweenDate(Date date1, Date date2)
  6. secondDiff(String startTime, String endTime)
  7. secondsBetween(Date dt1, Date dt2)
  8. getDateOffset()
  9. interval(Date date)