Get the length of a time frame in days rounded up. - Java java.util

Java examples for java.util:Time

Description

Get the length of a time frame in days rounded up.

Demo Code


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import org.apache.log4j.Logger;

public class Main{
    public static void main(String[] argv) throws Exception{
        Date start = new Date();
        Date end = new Date();
        System.out.println(getLengthInDays(start,end));
    }//from  ww w  .  j  a  va2 s  .  c o  m
    /**
     * Get the length of a timeframe in days rounded up. 
     */
    public static int getLengthInDays(Date start, Date end) {
        Calendar calStart = GregorianCalendar.getInstance();
        Calendar calEnd = GregorianCalendar.getInstance();

        /* Swap dates */
        if (end.before(start)) {
            calStart.setTime(end);
            calEnd.setTime(start);
        } else {
            calStart.setTime(start);
            calEnd.setTime(end);
        }

        CalendarUtils.setHoursMinutesAndSeconds(calStart, 0, 0, 0);
        CalendarUtils.setHoursMinutesAndSeconds(calEnd, 5, 0, 0);

        long endf = (long) calEnd.getTime().getTime();
        long startf = (long) calStart.getTime().getTime();

        long diffL = endf - startf;
        double diff = (diffL) / (24.0 * 3600.0 * 1000.0);
        double diffD = Math.ceil(diff);
        return (int) diffD;
    }
    public static void setHoursMinutesAndSeconds(Calendar cal, int hours,
            int minutes, int seconds) {
        cal.set(Calendar.HOUR_OF_DAY, hours);
        cal.set(Calendar.MINUTE, minutes);
        cal.set(Calendar.SECOND, seconds);
        cal.set(Calendar.MILLISECOND, 0);
    }
}

Related Tutorials