Java Day Between calculateDays(Date beginDate, Date endDate)

Here you can find the source of calculateDays(Date beginDate, Date endDate)

Description

Calculates difference between two days, in days

License

Apache License

Parameter

Parameter Description
beginDate a parameter
endDate a parameter

Return

difference in days

Declaration

public static long calculateDays(Date beginDate, Date endDate) 

Method Source Code

//package com.java2s;
/*/*w ww  .ja v  a2 s  .c  o m*/
 *    Copyright 2003, 2004, 2005, 2006 Research Triangle Institute
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 */

import java.util.Calendar;

import java.util.Date;
import java.util.GregorianCalendar;

import java.util.TimeZone;

public class Main {
    /**
     * Calculates difference between two days, in days
     * @param beginDate
     * @param endDate
     * @return difference in days
     */
    public static long calculateDays(Date beginDate, Date endDate) {
        GregorianCalendar beginCalendar = new GregorianCalendar();
        beginCalendar.setTime(beginDate);
        GregorianCalendar endCalendar = new GregorianCalendar();
        endCalendar.setTime(endDate);
        java.util.Date d1 = beginCalendar.getTime();
        java.util.Date d2 = endCalendar.getTime();
        long l1 = d1.getTime();
        long l2 = d2.getTime();
        // there are 86400 seconds in a day
        long diffSeconds = (l2 - l1) / 1000;
        long diffDays = diffSeconds / 86400;
        return diffDays;
    }

    public static String getTime() {
        Calendar cal = Calendar.getInstance(TimeZone.getDefault());
        String DATE_FORMAT = "HH:mm:ss";
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DATE_FORMAT);
        sdf.setTimeZone(TimeZone.getDefault());
        String now = sdf.format(cal.getTime());
        return now;
    }

    public static String getTime(Date date) {
        // Calendar cal = Calendar.getInstance(TimeZone.getDefault());
        String DATE_FORMAT = "HH:mm:ss";
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DATE_FORMAT);
        // sdf.setTimeZone(TimeZone.getDefault());
        String formattedTime = sdf.format(date);
        return formattedTime;
    }
}

Related

  1. calculateDayDifference(final Date a, final Date b)
  2. calculateDays(Date dateEarly, Date dateLater)
  3. calculateDifference(Date d1, Date d2)
  4. calculateDifferMonths(Date date1, Date date2, boolean isTruncate)
  5. calculateNumberOfDays(String dateStr)