Java Hour Next nextHour(Date then)

Here you can find the source of nextHour(Date then)

Description

next Hour

License

Apache License

Declaration

public static Date nextHour(Date then) 

Method Source Code

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

import java.util.Calendar;
import java.util.Date;

public class Main {
    private static final int[] incrementSequence = new int[] { Calendar.SECOND, Calendar.MINUTE,
            Calendar.HOUR_OF_DAY, Calendar.DAY_OF_MONTH, Calendar.MONTH, Calendar.YEAR, Calendar.ERA };

    public static Date nextHour(Date then) {
        return next(then, Calendar.HOUR_OF_DAY, 1, 10);
    }//  www  .ja  va2  s.  co  m

    public static Date nextHour() {
        return nextHour(new Date());
    }

    public static Date next(Date then, int calendarField, int multiple, int minimalDelta) {
        int calendarFieldIncrementIndex = getIncrementSequenceIndex(calendarField);
        int nextSmallestCalendarField = calendarFieldIncrementIndex > 0
                ? incrementSequence[calendarFieldIncrementIndex - 1]
                : Calendar.MILLISECOND;

        Calendar calThen = Calendar.getInstance();
        calThen.setTime(then);

        calThen.add(nextSmallestCalendarField, minimalDelta); // always at least a second late if its a minute, a minute of its an hour, etc ...

        Calendar calResult = (Calendar) calThen.clone();
        calResult.add(calendarField, multiple);
        for (int index = calendarFieldIncrementIndex - 1; index >= 0; --index)
            calResult.set(incrementSequence[index], incrementSequence[index] == Calendar.DAY_OF_MONTH ? 1 : 0);
        calResult.set(Calendar.MILLISECOND, 0); // we don't deal with sub second resolution

        if (calResult.before(calThen))
            calResult.add(calendarField, 1);

        return calResult.getTime();
    }

    public static Date next(Date then, int calendarField, int minimalDelta) {
        return next(then, calendarField, 1, minimalDelta);
    }

    private static int getIncrementSequenceIndex(int calendarFieldNumber) {
        for (int index = 0; index < incrementSequence.length; ++index)
            if (incrementSequence[index] == calendarFieldNumber)
                return index;

        return 0;
    }
}

Related

  1. nextHour(Date date)
  2. nextHour(Date date)