Java TimeUnit Calculate getDateDiff(final Date d1, final Date d2, final TimeUnit timeUnit)

Here you can find the source of getDateDiff(final Date d1, final Date d2, final TimeUnit timeUnit)

Description

Calculates the difference between 2 date objects and returns the result in the requested time units.

License

Apache License

Parameter

Parameter Description
d1 first date
d2 second date
timeUnit time unit desired. Example: TimeUnit.DAYS, TimeUnit.HOURS, TimeUnit.MILLISECONDS

Return

difference between the 2 dates

Declaration

public static long getDateDiff(final Date d1, final Date d2, final TimeUnit timeUnit) 

Method Source Code

//package com.java2s;
/*/*from  www . ja v a  2  s  .  co m*/
 * Copyright 2014 Scott J. Johnson (http://scottjjohnson.com)
 *
 * 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
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.util.Date;

import java.util.concurrent.TimeUnit;

public class Main {
    /**
     * Calculates the difference between 2 date objects and returns the result in the requested time units.
     *
     * @param d1       first date
     * @param d2       second date
     * @param timeUnit time unit desired. Example: TimeUnit.DAYS, TimeUnit.HOURS, TimeUnit.MILLISECONDS
     *
     * @return difference between the 2 dates
     */
    public static long getDateDiff(final Date d1, final Date d2, final TimeUnit timeUnit) {

        long differenceInMilliseconds = d2.getTime() - d1.getTime();
        return timeUnit.convert(differenceInMilliseconds, TimeUnit.MILLISECONDS);
    }
}

Related

  1. getBase(final TimeUnit unit)
  2. getBucketInMillis(int bucketSize, TimeUnit bucketUnit)
  3. getComingTime(Integer delta, TimeUnit unit)
  4. getDate(final TimeUnit unit, final int offset)
  5. getDateDiff(Date date1, Date date2, TimeUnit timeUnit)
  6. getDifference(Calendar initDate, Calendar endDate, TimeUnit units)
  7. getExpiringMap(long time, TimeUnit unit)
  8. getFragment(final Calendar calendar, final int fragment, final TimeUnit unit)
  9. getFutureDate(long delay, TimeUnit timeUnit)