Java Date to Time getTimeInterval(Date fromDate)

Here you can find the source of getTimeInterval(Date fromDate)

Description

get Time Interval

License

Apache License

Declaration

public static String getTimeInterval(Date fromDate) 

Method Source Code


//package com.java2s;
/*/* w  w w.ja  v  a 2  s .co  m*/
 * TimeUtil.java
 * 
 * Copyright (C) 2005-2008 Tommi Laukkanen
 * http://www.substanceofcode.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.Calendar;
import java.util.Date;

public class Main {
    public static String getTimeInterval(Date fromDate) {
        Calendar cal = Calendar.getInstance();
        Date currentDate = cal.getTime();
        return getTimeInterval(fromDate, currentDate);
    }

    /** 
     * 
     * @param startDate Interval start date time
     * @param endDate Interval end date time
     * @return Time interval in format hh:mm:ss
     */
    public static String getTimeInterval(Date startDate, Date endDate) {

        Calendar cal = Calendar.getInstance();
        cal.setTime(startDate);
        cal.setTime(endDate);

        long intervalSeconds = (endDate.getTime() - startDate.getTime()) / 1000L;
        long hours = intervalSeconds / 3600L;
        long minutes = (intervalSeconds % 3600L) / 60L;
        long days = hours / 24L;

        if (days > 1) {
            return String.valueOf(days) + " days";
        } else if (hours > 0) {
            if (hours == 1) {
                return String.valueOf(hours) + " hour";
            } else {
                return String.valueOf(hours) + " hours";
            }
        } else {
            return String.valueOf(minutes) + " mins";
        }
    }
}

Related

  1. getTimeDeltaValue(Date t, Date baseDate, String tDelta)
  2. getTimeFromDate(Date date)
  3. getTimeFromDate(final Date date)
  4. getTimeImMillis(Date date)
  5. getTimeInSeconds(Date date)
  6. getTimeIntervalMins(Date firstDate, Date lastDate)
  7. getTimeLocalWithoutDst(java.util.Date d)
  8. getTimeLocalWithoutDst(java.util.Date d)
  9. getTimeMargin(String dateTime)