Java Date Difference dateDiff(String startTime, String endTime, String format)

Here you can find the source of dateDiff(String startTime, String endTime, String format)

Description

date Diff

License

Apache License

Declaration

public static long[] dateDiff(String startTime, String endTime,
            String format) 

Method Source Code

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

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

import java.util.Date;

public class Main {
    public static long[] dateDiff(String startTime, String endTime) {
        return dateDiff(startTime, endTime, "yyyy-MM-dd");
    }//from w w  w  . ja  v a 2s . c o m

    public static long[] dateDiff(String startTime, String endTime,
            String format) {
        SimpleDateFormat sd = new SimpleDateFormat(format);

        long nd = 86400000L;

        long nh = 3600000L;

        long nm = 60000L;

        long ns = 1000L;

        long[] date = new long[4];
        try {
            long diff = sd.parse(endTime).getTime()
                    - sd.parse(startTime).getTime();

            long day = diff / nd;
            long hour = diff % nd / nh;
            long min = diff % nd % nh / nm;
            long sec = diff % nd % nh % nm / ns;

            date[0] = day;
            date[1] = hour;
            date[2] = min;
            date[3] = sec;
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return date;
    }

    public static String getTime(Date date) {
        return format(date, "HH:mm:ss");
    }

    public static String format(Date date, String format) {
        String result = "";
        try {
            if (date != null) {
                DateFormat dateFormat = new SimpleDateFormat(format);
                result = dateFormat.format(date);
            }
        } catch (Exception localException) {
        }
        return result;
    }

    public static String format(Date date) {
        return format(date, "yyyy-MM-dd");
    }
}

Related

  1. dateDiff(final Date date1, final Date date2)
  2. dateDiff(int category, Date date1, Date date2)
  3. dateDiff(int interval, Date begin, Date end)
  4. dateDiff(java.util.Date a, java.util.Date b)
  5. dateDiff(String startDate, String endDate)
  6. DateDiff(String strDateBegin, String strDateEnd, int iType)
  7. dateDiffer(String time1, String time2, String formatStr)
  8. dateDiffInDays(Date dateStart, Date dateEnd)
  9. dateDiffInDaysIgnoreTime(Date dateStart, Date dateEnd)