Example usage for org.apache.commons.lang3.time DateUtils addHours

List of usage examples for org.apache.commons.lang3.time DateUtils addHours

Introduction

In this page you can find the example usage for org.apache.commons.lang3.time DateUtils addHours.

Prototype

public static Date addHours(final Date date, final int amount) 

Source Link

Document

Adds a number of hours to a date returning a new object.

Usage

From source file:org.openmrs.ISO8601Duration.java

/**
 * Add this duration to given startDate//from   w  w w  .  j  a  v  a2  s.  c o m
 * 
 * @param startDate
 * @param frequency is used to calculate time to be added to startDate when duration unit is
 *            'Recurring Interval'
 * @return date which is startDate plus duration
 */
public Date addToDate(Date startDate, OrderFrequency frequency) {
    if (SECONDS_CODE.equals(code))
        return DateUtils.addSeconds(startDate, duration);
    if (MINUTES_CODE.equals(code))
        return DateUtils.addMinutes(startDate, duration);
    if (HOURS_CODE.equals(code))
        return DateUtils.addHours(startDate, duration);
    if (DAYS_CODE.equals(code))
        return DateUtils.addDays(startDate, duration);
    if (WEEKS_CODE.equals(code))
        return DateUtils.addWeeks(startDate, duration);
    if (MONTHS_CODE.equals(code))
        return DateUtils.addMonths(startDate, duration);
    if (YEARS_CODE.equals(code))
        return DateUtils.addYears(startDate, duration);
    if (RECURRING_INTERVAL_CODE.equals(code)) {
        if (frequency == null)
            throw new APIException("Frequency can not be null when duration in Recurring Interval");
        return DateUtils.addSeconds(startDate,
                (int) (duration * SECONDS_PER_DAY / frequency.getFrequencyPerDay()));
    }
    throw new APIException(String.format("Unknown code '%s' for ISO8601 duration units", code));
}

From source file:org.rippleosi.patient.appointments.store.OpenEHRAppointmentStore.java

private Map<String, Object> createFlatJsonContent(AppointmentDetails appointment) {

    Map<String, Object> content = new HashMap<>();

    content.put("ctx/language", "en");
    content.put("ctx/territory", "GB");

    String appointmentStart = DateFormatter.combineDateTime(appointment.getDateOfAppointment(),
            appointment.getTimeOfAppointment());
    String appointmentEnd = DateFormatter
            .toString(DateUtils.addHours(DateFormatter.toDate(appointmentStart), 1));

    content.put(APPOINTMENTS_PREFIX + "referral_to", appointment.getServiceTeam());
    content.put(APPOINTMENTS_PREFIX + "appointment_schedule/lower", appointmentStart);
    content.put(APPOINTMENTS_PREFIX + "appointment_schedule/upper", appointmentEnd);
    content.put(APPOINTMENTS_PREFIX + "receiver/address:0/location", appointment.getLocation());
    content.put(APPOINTMENTS_PREFIX + "ism_transition/current_state|value", appointment.getStatus());
    content.put(APPOINTMENTS_PREFIX + "time", DateFormatter.toString(appointment.getDateCreated()));

    return content;
}

From source file:org.silverpeas.core.date.AbstractDateDatable.java

@Override
public T addHours(final int amount) {
    return newInstanceFrom(DateUtils.addHours(this, amount));
}

From source file:org.silverpeas.core.util.DateUtilTest.java

@Test
public void testGetOutputDateAndHour() {
    Date date = DateUtil.resetHour(java.sql.Date.valueOf("2013-05-21"));
    assertThat(DateUtil.getOutputDateAndHour(date, LANGUAGE), is("05/21/2013"));

    Date year = DateUtils.addYears(date, 1);
    assertThat(DateUtil.getOutputDateAndHour(year, LANGUAGE), is("05/21/2014"));

    Date month = DateUtils.addMonths(date, 1);
    assertThat(DateUtil.getOutputDateAndHour(month, LANGUAGE), is("06/21/2013"));

    Date day = DateUtils.addDays(date, 1);
    assertThat(DateUtil.getOutputDateAndHour(day, LANGUAGE), is("05/22/2013"));

    Date hour = DateUtils.addHours(date, 1);
    assertThat(DateUtil.getOutputDateAndHour(hour, LANGUAGE), is("05/21/2013 01:00"));
    hour = DateUtils.addHours(date, 12);
    assertThat(DateUtil.getOutputDateAndHour(hour, LANGUAGE), is("05/21/2013 12:00"));
    hour = DateUtils.addHours(date, 22);
    assertThat(DateUtil.getOutputDateAndHour(hour, LANGUAGE), is("05/21/2013 22:00"));

    Date minute = DateUtils.addMinutes(date, 1);
    assertThat(DateUtil.getOutputDateAndHour(minute, LANGUAGE), is("05/21/2013 00:01"));
    minute = DateUtils.addMinutes(date, 59);
    assertThat(DateUtil.getOutputDateAndHour(minute, LANGUAGE), is("05/21/2013 00:59"));
    minute = DateUtils.addMinutes(date, 60);
    assertThat(DateUtil.getOutputDateAndHour(minute, LANGUAGE), is("05/21/2013 01:00"));
    minute = DateUtils.addMinutes(date, 61);
    assertThat(DateUtil.getOutputDateAndHour(minute, LANGUAGE), is("05/21/2013 01:01"));

    Date second = DateUtils.addSeconds(date, 1);
    assertThat(DateUtil.getOutputDateAndHour(second, LANGUAGE), is("05/21/2013 00:00"));
    second = DateUtils.addSeconds(date, 59);
    assertThat(DateUtil.getOutputDateAndHour(second, LANGUAGE), is("05/21/2013 00:00"));
    second = DateUtils.addSeconds(date, 60);
    assertThat(DateUtil.getOutputDateAndHour(second, LANGUAGE), is("05/21/2013 00:01"));
    second = DateUtils.addSeconds(date, 61);
    assertThat(DateUtil.getOutputDateAndHour(second, LANGUAGE), is("05/21/2013 00:01"));

    Date millisecond = DateUtils.addMilliseconds(date, 1);
    assertThat(DateUtil.getOutputDateAndHour(millisecond, LANGUAGE), is("05/21/2013 00:00"));
    millisecond = DateUtils.addMilliseconds(date, 999);
    assertThat(DateUtil.getOutputDateAndHour(millisecond, LANGUAGE), is("05/21/2013 00:00"));
    millisecond = DateUtils.addMilliseconds(date, 1000);
    assertThat(DateUtil.getOutputDateAndHour(millisecond, LANGUAGE), is("05/21/2013 00:00"));
    millisecond = DateUtils.addMilliseconds(date, 1001);
    assertThat(DateUtil.getOutputDateAndHour(millisecond, LANGUAGE), is("05/21/2013 00:00"));

    // 2013-05-21 23:59:59.999
    date = DateUtils.addHours(/*from   w  ww  .j  ava 2  s  . com*/
            DateUtils.addMinutes(DateUtils.addSeconds(DateUtils.addMilliseconds(date, 999), 59), 59), 23);
    assertThat(DateUtil.getOutputDateAndHour(date, LANGUAGE), is("05/21/2013 23:59"));

    // 2013-05-22 00:00:00.000
    date = DateUtils.addMilliseconds(date, 1);
    assertThat(DateUtil.getOutputDateAndHour(date, LANGUAGE), is("05/22/2013"));

    // 2013-05-22 00:00:00.001
    date = DateUtils.addMilliseconds(date, 1);
    assertThat(DateUtil.getOutputDateAndHour(date, LANGUAGE), is("05/22/2013 00:00"));
}

From source file:pl.bcichecki.rms.client.android.activities.EditEventActivity.java

protected void setUpForm(Bundle savedInstanceState) {
    if (savedInstanceState == null) {
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            originalEvent = (Event) extras.getSerializable(EDIT_EVENT_EXTRA);
        } else {/*from w  w  w. j a  v a  2  s  . c  om*/
            originalEvent = null;
        }
    } else {
        originalEvent = (Event) savedInstanceState.getSerializable(EDIT_EVENT_EXTRA);
    }

    eventCopy = PojoUtils.createDefensiveCopy(originalEvent);

    if (eventCopy == null) {
        Log.d(TAG, "No event to edit passed. Acting as new event form");

        editEventForm = false;

        Date now = new Date();
        startDate = DateUtils.addHours(now, 1);
        endDate = DateUtils.addHours(now, 2);

        setTitle(R.string.activity_edit_event_title_new);

    } else {
        Log.d(TAG, "Event to edit passed. Acting as edit event form");

        titleText.setText(eventCopy.getTitle());
        descriptionText.setText(eventCopy.getDescription());

        if (eventCopy.getType().equals(EventType.MEETING)) {
            meetingRdbtn.setChecked(true);
        }
        if (eventCopy.getType().equals(EventType.INTERVIEW)) {
            interviewRdbtn.setChecked(true);
        }

        startDate = eventCopy.getStartDate();
        endDate = eventCopy.getEndDate();

        pickedParticipants.clear();
        pickedParticipants.addAll(eventCopy.getParticipants());
        pickedDevices.clear();
        pickedDevices.addAll(eventCopy.getDevices());

        updateParticipantsText();
        updateDevicesText();
    }
}

From source file:tds.dll.mysql.SimDLL.java

public SingleDataResultSet SIM_CopySession2_SP(SQLConnection connection, UUID fromSession, String sessionName,
        String sessionDescription, String toUser) throws ReturnStatusException {
    Date starttime = _dateUtil.getDateWRetStatus(connection);
    Date now = starttime;/* ww  w . j a v a 2  s. c  o  m*/
    Date dateBegin = null, dateEnd = null;
    String status = "closed";
    String userId = null;
    String userName = null;
    UUID browserKey = null;
    Long proctorKey = null;
    String clientname = null;
    String client = null;
    String language = null;
    Integer sessionType = null;
    String originalId = null;

    final String cmd1 = " select ProctorID as userId,  ProctorName as userName, _efk_Proctor as proctorKey,"
            + "  _fk_Browser as browserKey, clientname, sim_language as language, sessionType,  clientname as client,"
            + " sessionID as originalID " + "  from session where _Key = ${fromSession}";
    SqlParametersMaps parms1 = (new SqlParametersMaps()).put("fromsession", fromSession);
    SingleDataResultSet rs1 = executeStatement(connection, cmd1, parms1, false).getResultSets().next();
    DbResultRecord rcd1 = rs1.getCount() > 0 ? rs1.getRecords().next() : null;
    if (rcd1 != null) {
        userId = rcd1.<String>get("userId");
        userName = rcd1.<String>get("userName");
        proctorKey = rcd1.<Long>get("proctorKey");
        browserKey = rcd1.<UUID>get("browserKey");
        clientname = rcd1.<String>get("clientname");
        language = rcd1.<String>get("language");
        sessionType = rcd1.<Integer>get("sessionType");
        client = rcd1.<String>get("client");
        originalId = rcd1.<String>get("originalId");
    }

    if (toUser != null) {
        final String cmd2 = "select userID,  userName,  userkey as proctorKey, browserkey "
                + " from sim_user where userID = ${toUser}";
        SqlParametersMaps parms2 = (new SqlParametersMaps()).put("toUser", toUser);
        SingleDataResultSet rs2 = executeStatement(connection, cmd2, parms2, false).getResultSets().next();
        DbResultRecord rcd2 = rs2.getCount() > 0 ? rs2.getRecords().next() : null;
        if (rcd2 != null) {
            userId = rcd2.<String>get("userId");
            userName = rcd2.<String>get("userName");
            proctorKey = rcd2.<Long>get("proctorKey");
            browserKey = rcd2.<UUID>get("browserKey");
        }
        sessionName = String.format("Copy of %s", originalId);
    }

    String environment = null;
    final String cmd3 = "select  environment from externs where clientname = ${clientname}";
    SqlParametersMaps parms3 = (new SqlParametersMaps()).put("clientname", clientname);
    SingleDataResultSet rs3 = executeStatement(connection, cmd3, parms3, false).getResultSets().next();
    DbResultRecord rcd3 = (rs3.getCount() > 0 ? rs3.getRecords().next() : null);
    if (rcd3 != null) {
        environment = rcd3.<String>get("environment");
    }
    if (environment == null || "SIMULATION".equals(environment) == false) {
        return _commonDll._ReturnError_SP(connection, clientname, "SIM_CopySession2",
                "Unknown client or wrong environment", clientname, null, null);
    }

    if (browserKey == null) {
        return _commonDll._ReturnError_SP(connection, client, "SIM_CopySession2", "Unknown session");
    }

    final String cmd4 = "select _fk_simuser from sim_userclient where _fk_simUser = ${userID} and clientname = ${clientname}";
    SqlParametersMaps parms4 = (new SqlParametersMaps()).put("clientname", clientname).put("userId", userId);
    if (!exists(executeStatement(connection, cmd4, parms4, false))) {
        return _commonDll._ReturnError_SP(connection, clientname, "SIM_CopySession2",
                "User is not authorized on this client");
    }

    String prefix = _commonDll._CoreSessName_FN(connection, clientname, userName);
    UUID sessionKey = UUID.randomUUID();

    if (dateBegin == null)
        dateBegin = now;

    if (dateEnd == null) {
        dateEnd = DateUtils.addHours(dateBegin, 80);
    } else if (DbComparator.lessOrEqual(dateEnd, dateBegin)) {
        dateEnd = DateUtils.addHours(dateBegin, 80);
    }

    if (DbComparator.greaterOrEqual(now, dateBegin) && DbComparator.lessOrEqual(now, dateEnd)) {
        status = "open";
    }

    _Ref<String> sessionIdRef = new _Ref<>();
    _commonDll._CreateClientSessionID_SP(connection, clientname, prefix, sessionIdRef);
    if (sessionIdRef.get() == null) {
        return _commonDll._ReturnError_SP(connection, client, "SIM_CopySession2",
                "Failed to create new session ID");
    }

    try {
        final String cmd5 = "insert into session "
                + " (_Key, `Name`, sim_language, _efk_Proctor, ProctorID, ProctorName, "
                + "  `status`, DateBegin, DateEnd, "
                + "   SessionID, _fk_browser, clientname, environment, dateVisited, sessiontype, description,"
                + "   datecreated, serveraddress) "
                + " values (${sessionKey}, ${sessionName}, ${language}, ${proctorKey}, ${userID}, ${userName}, "
                + "         ${status}, ${dateBegin}, ${dateEnd},"
                + "         ${sessionID}, ${browserKey}, ${clientname}, ${environment}, now(3), ${sessiontype}, ${sessionDescription}, "
                + "         now(3), ${localhost})";
        SqlParametersMaps parms5 = (new SqlParametersMaps()).put("sessionKey", sessionKey)
                .put("sessionName", sessionName).put("language", language).put("proctorKey", proctorKey)
                .put("userId", userId).put("userName", userName).put("status", status)
                .put("dateBegin", dateBegin).put("dateEnd", dateEnd).put("sessionId", sessionIdRef.get())
                .put("browserKey", browserKey).put("clientname", clientname).put("environment", environment)
                .put("sessionType", sessionType).put("sessionDescription", sessionDescription)
                .put("localhost", _commonDll.getLocalhostName());

        Integer insertedCnt = executeStatement(connection, cmd5, parms5, false).getUpdateCount();

    } catch (ReturnStatusException re) {
        String err = re.getMessage();
        _commonDll._LogDBError_SP(connection, "SIM_CopySession2", err, null, null, null, null, clientname,
                null);
        return _commonDll._ReturnError_SP(connection, client, "SIM_CopySession",
                "Failed to insert new session into database");
    }

    final String cmd6 = "INSERT INTO sessiontests(_fk_Session, _efk_AdminSubject, _efk_TestID, iterations, "
            + "   opportunities, meanProficiency, sdProficiency, strandCorrelation, sim_threads, sim_thinkTime, handscoreitemtypes) "
            + " SELECT ${sessionKey}, _efk_AdminSubject, _efk_TestID, iterations, "
            + "        opportunities, meanProficiency, sdProficiency, strandCorrelation, sim_threads, sim_thinkTime, handscoreitemtypes "
            + " FROM sessiontests where _fk_Session = ${fromSession}";
    SqlParametersMaps parms6 = (new SqlParametersMaps()).put("sessionKey", sessionKey).put("fromSession",
            fromSession);

    Integer insertedCnt = executeStatement(connection, cmd6, parms6, false).getUpdateCount();

    final String cmd7 = "INSERT INTO sim_segment(_fk_session, _efk_AdminSubject, _efk_Segment, StartAbility, StartInfo, MinItems, MaxItems "
            + "  , FTStartPos, FTEndPos, FTMinItems, FTMaxItems "
            + "  , formSelection, blueprintWeight, cset1size, cset2Random, cset2InitialRandom, loadConfig, updateConfig, itemWeight"
            + "  , abilityOffset, segmentPosition, segmentID, selectionAlgorithm, cset1Order "
            + "  , rcAbilityWeight, abilityWeight, precisionTargetNotMetWeight, precisionTargetMetWeight, precisionTarget, adaptiveCut, tooCloseSEs "
            + "  , terminationMinCount, terminationOverallInfo, terminationRCInfo, terminationTooClose, terminationFlagsAnd) "
            + " SELECT ${sessionKey}, _efk_AdminSubject, _efk_Segment, StartAbility, StartInfo, MinItems, MaxItems"
            + "  , FTStartPos, FTEndPos, FTMinItems, FTMaxItems "
            + "  , formSelection, blueprintWeight, cset1size, cset2Random, cset2InitialRandom, loadConfig, updateConfig, itemWeight "
            + "  , abilityOffset, segmentPosition, segmentID, selectionAlgorithm, cset1Order "
            + "  , rcAbilityWeight, abilityWeight, precisionTargetNotMetWeight, precisionTargetMetWeight, precisionTarget, adaptiveCut, tooCloseSEs "
            + "  , terminationMinCount, terminationOverallInfo, terminationRCInfo, terminationTooClose, terminationFlagsAnd "
            + "FROM sim_segment where _fk_Session = ${fromSession}";
    SqlParametersMaps parms7 = (new SqlParametersMaps()).put("sessionKey", sessionKey).put("fromSession",
            fromSession);
    insertedCnt = executeStatement(connection, cmd7, parms7, false).getUpdateCount();

    final String cmd8 = "INSERT INTO sim_segmentcontentlevel( "
            + "   _fk_Session, _efk_Segment, contentLevel, MinItems, MaxItems, AdaptiveCut, StartAbility, StartInfo, Scalar, IsStrictmax, bpweight"
            + "  ,abilityWeight, precisionTargetNotMetWeight, precisionTargetMetWeight, precisionTarget) "
            + "SELECT ${sessionKey}, _efk_Segment, contentLevel, MinItems, MaxItems, AdaptiveCut, StartAbility, StartInfo, Scalar, IsStrictmax, bpweight"
            + "  ,abilityWeight, precisionTargetNotMetWeight, precisionTargetMetWeight, precisionTarget "
            + "FROM sim_segmentcontentlevel where _fk_Session = ${fromSession}";
    SqlParametersMaps parms8 = (new SqlParametersMaps()).put("sessionKey", sessionKey).put("fromSession",
            fromSession);
    insertedCnt = executeStatement(connection, cmd8, parms8, false).getUpdateCount();

    final String cmd9 = "INSERT INTO sim_segmentitem("
            + "  _fk_Session, _efk_Segment, _efk_Item, isActive, isRequired, isFieldTest, strand, groupID) "
            + "SELECT ${sessionKey}, _efk_Segment, _efk_Item, isActive, isRequired, isFieldTest, strand, groupID "
            + "FROM sim_segmentitem where _fk_session = ${fromSession}";
    SqlParametersMaps parms9 = (new SqlParametersMaps()).put("sessionKey", sessionKey).put("fromSession",
            fromSession);
    insertedCnt = executeStatement(connection, cmd9, parms9, false).getUpdateCount();

    final String cmd10 = "INSERT INTO sim_itemgroup(_fk_Session, _efk_Segment, groupID, maxItems) "
            + "SELECT ${sessionKey}, _efk_Segment, groupID, maxItems "
            + "FROM sim_itemgroup where _fk_Session = ${fromSession}";
    SqlParametersMaps parms10 = (new SqlParametersMaps()).put("sessionKey", sessionKey).put("fromSession",
            fromSession);
    insertedCnt = executeStatement(connection, cmd10, parms10, false).getUpdateCount();

    final String cmd12 = "insert into sim_sessiontestpackage(_fk_session, _fk_adminsubject, _fk_testpackage) "
            + "select ${sessionKey}, _fk_adminsubject, _fk_testpackage "
            + "from sim_sessiontestpackage where _fk_Session = ${fromSession}";
    SqlParametersMaps parms12 = (new SqlParametersMaps()).put("sessionKey", sessionKey).put("fromSession",
            fromSession);
    insertedCnt = executeStatement(connection, cmd12, parms12, false).getUpdateCount();

    final String cmd11 = "select 'success' as status, ${sessionKey} as sessionKey, ${sessionID} as sessionID, ${sessionName} as `Name`, "
            + " ${status} as sessionStatus, "
            + " bigtoint((select count(*) from sessiontests where _fk_Session = ${sessionKey})) as tests";
    SqlParametersMaps parms11 = (new SqlParametersMaps()).put("sessionKey", sessionKey)
            .put("sessionId", sessionIdRef.get()).put("sessionName", sessionName).put("status", status);
    SingleDataResultSet rs11 = executeStatement(connection, cmd11, parms11, false).getResultSets().next();

    _commonDll._LogDBLatency_SP(connection, "SIM_CopySession2", starttime, proctorKey, true, null, null,
            sessionKey, clientname, null);
    return rs11;
}

From source file:ubic.basecode.util.DateUtil.java

/**
 * Turn a string like '-7d' into the date equivalent to "seven days ago". Supports 'd' for day, 'h' for hour, 'm'
 * for minutes, "M" for months and "y" for years. Start with a '-' to indicate times in the past ('+' is not
 * necessary for future). Values must be integers.
 * /*from  ww w .  j  a va2s .c om*/
 * @param date to be added/subtracted to
 * @param dateString
 * @author Paul Pavlidis
 * @return Date relative to 'now' as modified by the input date string.
 */
public static Date getRelativeDate(Date date, String dateString) {

    if (date == null)
        throw new IllegalArgumentException("Null date");

    Pattern pat = Pattern.compile("([+-]?[0-9]+)([dmhMy])");

    Matcher match = pat.matcher(dateString);
    boolean matches = match.matches();

    if (!matches) {
        throw new IllegalArgumentException(
                "Couldn't make sense of " + dateString + ", please use something like -7d or -8h");
    }

    int amount = Integer.parseInt(match.group(1).replace("+", ""));
    String unit = match.group(2);

    if (unit.equals("h")) {
        return DateUtils.addHours(date, amount);
    } else if (unit.equals("m")) {
        return DateUtils.addMinutes(date, amount);
    } else if (unit.equals("d")) {
        return DateUtils.addDays(date, amount);
    } else if (unit.equals("y")) {
        return DateUtils.addYears(date, amount);
    } else if (unit.equals("M")) {
        return DateUtils.addMonths(date, amount);
    } else {
        throw new IllegalArgumentException(
                "Couldn't make sense of units in " + dateString + ", please use something like -7d or -8h");
    }

}

From source file:ubic.gemma.core.analysis.preprocess.batcheffects.BatchInfoPopulationHelperServiceImpl.java

/**
 * @param  earlierDate earlier date/*  w ww  . j  a v  a 2  s.c  o m*/
 * @param  date        data
 * @return             false if 'date' is considered to be in the same batch as 'earlierDate', true if we should
 *                     treat it as a
 *                     separate batch.
 */
private boolean gapIsLarge(Date earlierDate, Date date) {
    return !DateUtils.isSameDay(date, earlierDate)
            && DateUtils
                    .addHours(earlierDate,
                            BatchInfoPopulationHelperServiceImpl.MAX_GAP_BETWEEN_SAMPLES_TO_BE_SAME_BATCH)
                    .before(date);
}

From source file:ubic.gemma.core.analysis.preprocess.batcheffects.BatchInfoPopulationServiceTest.java

@Test
public void testDatesToBatchA() {
    BatchInfoPopulationHelperServiceImpl ser = new BatchInfoPopulationHelperServiceImpl();

    Calendar cal = Calendar.getInstance();
    cal.set(2004, Calendar.APRIL, 10, 10, 1, 1);
    Date d = cal.getTime();/*  www.  j  ava2s  .  c om*/

    Collection<Date> dates = new HashSet<>();

    dates.add(d);
    dates.add(DateUtils.addHours(d, 1)); // first batch
    dates.add(DateUtils.addHours(d, 2)); // first batch
    dates.add(DateUtils.addHours(d, 3)); // first batch
    dates.add(DateUtils.addHours(d, 24)); // second batch
    dates.add(DateUtils.addHours(d, 25));// second batch
    dates.add(DateUtils.addHours(d, 26));// second batch
    dates.add(DateUtils.addHours(d, 27));// second batch

    Map<String, Collection<Date>> actual = ser.convertDatesToBatches(dates);

    /*
     * How many unique values?
     */
    Set<String> s = new HashSet<>(actual.keySet());
    assertEquals(2, s.size());
}

From source file:ubic.gemma.core.analysis.preprocess.batcheffects.BatchInfoPopulationServiceTest.java

@Test
public void testDatesToBatchB() {
    BatchInfoPopulationHelperServiceImpl ser = new BatchInfoPopulationHelperServiceImpl();
    Calendar cal = Calendar.getInstance();
    cal.set(2004, Calendar.APRIL, 10);
    Date d = cal.getTime();/*from ww w.j a  v  a  2  s  . c  o m*/

    Collection<Date> dates = new HashSet<>();

    dates.add(d);

    dates.add(DateUtils.addSeconds(d, 3500));// first batch, all within two hours of each other.
    dates.add(DateUtils.addSeconds(d, 7000));// first batch, all within two hours of each other.
    dates.add(DateUtils.addSeconds(d, 8000));// first batch, all within two hours of each other.
    dates.add(DateUtils.addHours(d, 2226));// second batch, but singleton merged backwards

    dates.add(DateUtils.addHours(d, 11124));// third batch , but second was a singleton so we're only on #2.
    dates.add(DateUtils.addHours(d, 11125));// third batch, but gets merged in with second.
    dates.add(DateUtils.addHours(d, 11189)); // fourth batch, but gets merged in with second.

    Map<String, Collection<Date>> actual = ser.convertDatesToBatches(dates);

    /*
     * How many unique values?
     */
    Set<String> s = new HashSet<>(actual.keySet());
    assertEquals(2, s.size());

    this.debug(actual);
}