Example usage for java.util Calendar before

List of usage examples for java.util Calendar before

Introduction

In this page you can find the example usage for java.util Calendar before.

Prototype

public boolean before(Object when) 

Source Link

Document

Returns whether this Calendar represents a time before the time represented by the specified Object.

Usage

From source file:mchs.neverforget.NeverForgetActivity.java

private void setupInformativeColors() {
    @SuppressLint("SimpleDateFormat")
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy");
    for (Book b : bookArrayList) {
        Calendar returnDate = new GregorianCalendar();
        Calendar currentDate = new GregorianCalendar();
        try {/*from   ww w.ja  va2s  . c  om*/
            returnDate.setTime(sdf.parse(b.getReturnDate()));
            currentDate.setTime(sdf.parse(sdf.format(System.currentTimeMillis())));
            if (returnDate.before(currentDate)) {
                b.setDrawableId(R.drawable.item_book_expired);
            } else {
                int days = daysBetween(returnDate, currentDate);
                if (days < 2) {
                    b.setDrawableId(R.drawable.item_book_red);
                } else
                    b.setDrawableId(R.drawable.item_book);
            }
        } catch (ParseException e) {
            e.printStackTrace();

        }
    }
}

From source file:com.sean.takeastand.storage.ScheduleEditor.java

public void editStartTime(boolean alarmToday, AlarmSchedule alarmSchedule) {
    int UID = alarmSchedule.getUID();
    Calendar startTime = alarmSchedule.getStartTime();
    cancelDailyRepeatingAlarm(UID);
    setDailyRepeatingAlarm(UID, Utils.calendarToTimeString(startTime));
    scheduleDatabaseAdapter.updateStartTime(UID, Utils.calendarToTimeString(startTime));
    if (alarmToday && alarmSchedule.getActivated()) {
        Log.i(TAG, "alarmToday and activated");
        FixedAlarmSchedule fixedAlarmSchedule = new FixedAlarmSchedule(alarmSchedule);
        Calendar endTime = alarmSchedule.getEndTime();
        Calendar rightNow = Calendar.getInstance();
        if (startTime.before(rightNow) && endTime.after(rightNow)) {
            ScheduledRepeatingAlarm scheduledRepeatingAlarm = new ScheduledRepeatingAlarm(mContext,
                    fixedAlarmSchedule);
            //Update cancels the original alarm, so image needs to be set again
            scheduledRepeatingAlarm.updateAlarm();
            Utils.setImageStatus(mContext, Constants.SCHEDULE_RUNNING);
        } else {/*from   w w w.  j  a  v a  2s  .c  o  m*/
            if (UID == Utils.getRunningScheduledAlarm(mContext)) {
                new ScheduledRepeatingAlarm(mContext, fixedAlarmSchedule).cancelAlarm();
            }
        }
    }

}

From source file:com.intuit.wasabi.tests.service.IntegrationExperiment.java

/**
 * Checks if an experiment is created in a 15 second time window and yields all the correct data.
 *
 * @throws java.text.ParseException if the dates are not correctly formatted.
 *///from w  ww  .j  a v a 2s .  c o m
@Test(dependsOnGroups = { "ping" })
public void t_createAndValidateExperiment() throws java.text.ParseException {
    Calendar now = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    now.add(Calendar.SECOND, -2); // adjust: drops milliseconds. -2 to avoid all problems with that
    Calendar latest = (Calendar) now.clone();
    latest.add(Calendar.SECOND, 15);
    Experiment created = postExperiment(completeExperiment);
    completeExperiment.setState(Constants.EXPERIMENT_STATE_DRAFT);
    assertEqualModelItems(created, completeExperiment, new DefaultNameExclusionStrategy("id", "creationTime",
            "modificationTime", "results", "ruleJson", "hypothesisIsCorrect"));

    String nowStr = TestUtils.getTimeString(now);
    String latestStr = TestUtils.getTimeString(latest);
    Calendar creationTime = TestUtils.parseTime(created.creationTime);
    Assert.assertTrue(creationTime.after(now) && creationTime.before(latest),
            "Creation time is not in the correct interval.\nEarly:   " + nowStr + "\nCreated: "
                    + created.creationTime + "\nLate:    " + latestStr);

    Calendar modificationTime = TestUtils.parseTime(created.modificationTime);
    Assert.assertTrue(modificationTime.after(now) && modificationTime.before(latest),
            "Modification time is not in the correct interval.\nEarly:   " + nowStr + "\nCreated: "
                    + created.modificationTime + "\nLate:    " + latestStr);

    Assert.assertEquals(created.creationTime, created.modificationTime,
            "Creation and Modification are not equal.");

    completeExperiment.update(created);
}

From source file:com.heliumv.api.production.ProductionApi.java

private int daysBetween(Calendar startDate, Calendar endDate) {
    Calendar date = (Calendar) startDate.clone();
    int daysBetween = 0;
    while (date.before(endDate)) {
        date.add(Calendar.DAY_OF_MONTH, 1);
        daysBetween++;/*from   w  w  w . j  a  v a 2 s  .c  o  m*/
    }
    return daysBetween;
}

From source file:org.rapidandroid.activity.chart.ChartBroker.java

/**
 * Gets the display type for this, based on the start and end dates
 * //from  ww  w .  ja  v a  2  s .c o m
 * @return
 */
protected DateDisplayTypes getDisplayType(Date startDate, Date endDate) {
    Calendar startCal = Calendar.getInstance();
    startCal.setTime(startDate);
    Calendar endCal = Calendar.getInstance();
    endCal.setTime(endDate);

    Calendar tempCal = Calendar.getInstance();
    tempCal.setTime(startDate);
    tempCal.add(Calendar.DATE, 3);
    if (endCal.before(tempCal)) {
        // within 3 days, we do it by hour. with day shading
        return DateDisplayTypes.Hourly;
    }

    tempCal.setTime(startDate);
    tempCal.add(Calendar.MONTH, 3);

    if (endCal.before(tempCal)) {
        // within 3 months, we break it down by day with week & month
        // shading?
        return DateDisplayTypes.Daily;
    }
    tempCal.setTime(startDate);
    tempCal.add(Calendar.YEAR, 2);
    if (endCal.before(tempCal)) {
        // within 2 years, we break it down by week with month shading
        return DateDisplayTypes.Weekly;
    }
    tempCal.setTime(startDate);
    tempCal.add(Calendar.YEAR, 4);

    if (endCal.before(tempCal)) {
        // 2-4 years break it down by month with year shading
        return DateDisplayTypes.Monthly;
    } else { // if(endCal.get(Calendar.YEAR) - startCal.get(Calendar.YEAR)
             // >= 4) {
             // we need to break it down by year. with year shading
        return DateDisplayTypes.Yearly;
    }
}

From source file:org.kuali.kfs.gl.batch.service.impl.RunDateServiceImpl.java

/**
 * Determines if the given calendar time is before the given cutoff time
 * //  www  .  ja  va  2s . c o m
 * @param currentCal the current time
 * @param cutoffTime the "start of the day" cut off time
 * @return true if the current time is before the cutoff, false otherwise
 */
protected boolean isCurrentDateBeforeCutoff(Calendar currentCal, CutoffTime cutoffTime) {
    if (cutoffTime != null) {
        // if cutoff date is not properly defined
        // 24 hour clock (i.e. hour is 0 - 23)

        // clone the calendar so we get the same month, day, year
        // then change the hour, minute, second fields
        // then see if the cutoff is before or after
        Calendar cutoffCal = (Calendar) currentCal.clone();
        cutoffCal.setLenient(false);
        cutoffCal.set(Calendar.HOUR_OF_DAY, cutoffTime.hour);
        cutoffCal.set(Calendar.MINUTE, cutoffTime.minute);
        cutoffCal.set(Calendar.SECOND, cutoffTime.second);
        cutoffCal.set(Calendar.MILLISECOND, 0);

        return currentCal.before(cutoffCal);
    }
    // if cutoff date is not properly defined, then it is considered to be after the cutoff
    return false;
}

From source file:com.krawler.common.util.StringUtil.java

public static Boolean isLessthanDates(Long olddate, Long newdate) {
    boolean flag = false;
    try {// w  w w .  j a v a 2s .c om
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd 00:00:00");
        Calendar olddt = Calendar.getInstance();
        olddt.setTime(sdf.parse(sdf.format(new Date(olddate))));

        Calendar newdt = Calendar.getInstance();
        newdt.setTime(sdf.parse(sdf.format(new Date(newdate))));
        flag = olddt.before(newdt);
    } catch (ParseException ex) {
        LOG.info("Can't parse the date in isLessthanDates() : ", ex);
    }
    return flag;
}

From source file:es.udc.fic.test.model.ClasificacionServiceTest.java

@Test
public void getClasificacionTest() {

    //Creamos una sola regata con la instancia de todos los objetos en memoria
    Regata regata = new Regata();
    regata.setNombre("Mock Regata");
    regata.setDescripcion("Mock Desc");
    regataDao.save(regata);/*from w  w  w.  j  a  va  2s.co m*/

    Tipo tipoCatamaran = new Tipo("Catamarn", "Desc Catamarn", false);
    tipoDao.save(tipoCatamaran);

    Tipo tipoCrucero = new Tipo("Crucero", "Desc Crucero", false);
    tipoDao.save(tipoCrucero);

    Tipo tipoLigero = new Tipo("Vela ligera", "Desc Vela ligera", true);
    tipoDao.save(tipoLigero);

    Barco b1 = new Barco(204566, "Juan Sebastian El Cano", tipoCatamaran, new Float(1.5), "Lagoon 421");
    inscripcionService.inscribir(regata, b1, "Iago Surez");
    Barco b2 = new Barco(199012, "El Holandes Errante", tipoCrucero, new Float(2.5), "SWAN 66 FD");
    inscripcionService.inscribir(regata, b2, "Samu Paredes");
    Barco b3 = new Barco(201402, "La Perla Negra", tipoCrucero, new Float(1.5), "X6");
    inscripcionService.inscribir(regata, b3, "Adrian Pallas");
    Barco b4 = new Barco(202102, "La Pinta", tipoCrucero, new Float(1.5), "X6");
    inscripcionService.inscribir(regata, b4, "Pedro Cabalar");
    Barco b5 = new Barco(182345, "Venus", tipoLigero, null, "Laser Standar");
    inscripcionService.inscribir(regata, b5, "Jesus Lopez");
    Barco b6 = new Barco(206745, "Apolo", tipoLigero, null, "Laser Radial");
    inscripcionService.inscribir(regata, b6, "Diego Bascoy");

    Calendar dia1 = Calendar.getInstance();
    dia1.add(Calendar.DAY_OF_YEAR, -18);

    Calendar dia2 = Calendar.getInstance();
    dia2.add(Calendar.DAY_OF_YEAR, -18);
    dia2.add(Calendar.HOUR, 2);

    Calendar dia3 = Calendar.getInstance();
    dia3.add(Calendar.DAY_OF_YEAR, -17);

    Manga manga1 = new Manga(dia1, regata, null, 100);
    Manga manga2 = new Manga(dia2, regata, null, 100);
    Manga manga3 = new Manga(dia3, regata, null, 100);

    List<Posicion> posManga1 = new ArrayList<Posicion>();

    posManga1.add(new Posicion(new Long(3600), Posicion.Penalizacion.ZFP, manga1, b1, (long) 0));
    posManga1.add(new Posicion(new Long(3700), Posicion.Penalizacion.NAN, manga1, b2, (long) 0));
    posManga1.add(new Posicion(new Long(3750), Posicion.Penalizacion.ZFP, manga1, b3, (long) 0));
    posManga1.add(new Posicion(new Long(3900), Posicion.Penalizacion.NAN, manga1, b4, (long) 0));
    posManga1.add(new Posicion(new Long(3400), Posicion.Penalizacion.NAN, manga1, b5, (long) 0));
    posManga1.add(new Posicion(new Long(2400), Posicion.Penalizacion.SCP, manga1, b6, (long) 0));
    manga1.setPosiciones(posManga1);

    mangaService.cerrarYGuardarManga(manga1);
    regata.addManga(manga1);

    List<Posicion> posManga2 = new ArrayList<Posicion>();

    posManga2.add(new Posicion(new Long(3400), Posicion.Penalizacion.ZFP, manga2, b1, (long) 0));
    posManga2.add(new Posicion(new Long(3600), Posicion.Penalizacion.NAN, manga2, b2, (long) 0));
    posManga2.add(new Posicion(new Long(3950), Posicion.Penalizacion.ZFP, manga2, b3, (long) 0));
    posManga2.add(new Posicion(new Long(3200), Posicion.Penalizacion.NAN, manga2, b4, (long) 0));
    posManga2.add(new Posicion(new Long(3100), Posicion.Penalizacion.ZFP, manga2, b5, (long) 0));
    posManga2.add(new Posicion(new Long(2800), Posicion.Penalizacion.SCP, manga2, b6, (long) 0));
    manga2.setPosiciones(posManga2);
    mangaService.cerrarYGuardarManga(manga2);
    regata.addManga(manga2);

    List<Posicion> posManga3 = new ArrayList<Posicion>();

    posManga3.add(new Posicion(new Long(13500), Posicion.Penalizacion.SCP, manga3, b1, (long) 0));
    posManga3.add(new Posicion(new Long(13200), Posicion.Penalizacion.NAN, manga3, b2, (long) 0));
    posManga3.add(new Posicion(new Long(13350), Posicion.Penalizacion.NAN, manga3, b3, (long) 0));
    posManga3.add(new Posicion(new Long(13900), Posicion.Penalizacion.ZFP, manga3, b4, (long) 0));
    posManga3.add(new Posicion(new Long(14400), Posicion.Penalizacion.NAN, manga3, b5, (long) 0));
    posManga3.add(new Posicion(new Long(15400), Posicion.Penalizacion.SCP, manga3, b6, (long) 0));
    manga3.setPosiciones(posManga3);
    mangaService.cerrarYGuardarManga(manga3);
    regata.addManga(manga3);

    //        //Mostrar los datos:
    //        for(List<Posicion> lp : posicionesGeneralFinal){
    //            int total = 0;
    //            System.out.print(lp.get(0).getBarco().getVela() + ": ");
    //            for(Posicion p : lp){
    //                System.out.print(p.getPuntos() + " | ");
    //                total += p.getPuntos();
    //            }
    //            System.out.println("Tot: " + total);
    //        }

    //Testeamos la clasificacion Final por Tipo
    Tipo tipo = tipoCrucero;
    List<List<Posicion>> posicionesFinalTipo = regataService.getClasificacion(regata, null, tipo);

    //Comprobamos que estn todos los barcos y que no estn repetido
    assertEquals(inscripcionService.getInscripcionesByTipo(regata, tipo).size(), posicionesFinalTipo.size());

    //Comprobamos que hay tantas posiciones como mangas
    for (List<Posicion> posBarco : posicionesFinalTipo) {
        assertEquals(posBarco.size(), regata.getMangas().size());
    }

    //Comprobamos que todas las posiciones de la misma sublista pertenecen 
    // al mismo Barco.
    for (List<Posicion> posBarco : posicionesFinalTipo) {
        Barco barcoAct = posBarco.get(0).getBarco();
        for (Posicion p : posBarco) {
            assertEquals(barcoAct, p.getBarco());
        }
    }

    Calendar fechaAnterior = null;
    //Comprobamos que las listas internas estn ordenadas por la fecha de 
    // la manga
    for (List<Posicion> posBarco : posicionesFinalTipo) {
        for (int i = 0; i < posBarco.size(); i++) {
            Calendar fechaActual = posBarco.get(i).getManga().getFecha();
            if (i > 0) {
                //Comparamos los calendars:
                assertTrue(fechaAnterior.before(fechaActual));
            }
            fechaAnterior = fechaActual;
        }
    }

    int puntActual;
    int puntAnterior = 0;
    //Comprobamos que el resultado viene bien ordenado por la puntuacion
    for (List<Posicion> posBarco : posicionesFinalTipo) {
        puntActual = 0;
        for (Posicion p : posBarco) {
            puntActual += p.getPuntos();
        }
        assertTrue(puntActual >= puntAnterior);
        puntAnterior = puntActual;
    }

    for (List<Posicion> posBarco : posicionesFinalTipo) {
        for (Posicion posicion : posBarco) {
            assertEquals(tipo, posicion.getBarco().getTipo());
        }
    }

    //Testeamos la clasificacion General por Dia
    Calendar dia = dia2;
    List<List<Posicion>> posicionesDiaGeneral = regataService.getClasificacion(regata, dia, null);

    for (List<Posicion> posBarco : posicionesDiaGeneral) {
        for (Posicion posicion : posBarco) {
            assertTrue(TimeUtil.compareByDay(dia, posicion.getManga().getFecha()));
        }
    }

    //Testeamos la clisificacion de un Tipo en un Dia
    Tipo tipoEspecifico = tipoCrucero;
    Calendar diaEspecifico = dia2;
    List<List<Posicion>> posicionesDiaTipo = regataService.getClasificacion(regata, diaEspecifico,
            tipoEspecifico);

    for (List<Posicion> posBarco : posicionesDiaTipo) {
        for (Posicion posicion : posBarco) {
            assertEquals(tipoEspecifico, posicion.getBarco().getTipo());
            assertTrue(TimeUtil.compareByDay(diaEspecifico, posicion.getManga().getFecha()));
        }
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.BasicValidation.java

public String validate(String validationType, String value) {
    // Required field validation.
    // For literals, testing empty required values in validateLiterals.
    // This case may be needed for validation of other field types.
    if ("nonempty".equalsIgnoreCase(validationType)) {
        if (isEmpty(value))
            return REQUIRED_FIELD_EMPTY_MSG;
    }//w ww . j  a  v  a 2  s  . c  o  m
    // Format validation
    else if ("isDate".equalsIgnoreCase(validationType)) {
        if (isDate(value))
            return SUCCESS;
        else
            return "must be in valid date format mm/dd/yyyy.";
    } else if (validationType.indexOf("datatype:") == 0) {
        String datatypeURI = validationType.substring(9);
        String errorMsg = validateAgainstDatatype(value, datatypeURI);
        if (errorMsg == null) {
            return SUCCESS;
        } else {
            return errorMsg;
        }
    } else if ("httpUrl".equalsIgnoreCase(validationType)) {
        //check if it has http or https, we could do more but for now this is all.
        if (!value.startsWith("http://") && !value.startsWith("https://")) {
            return "This URL must start with http:// or https://";
        } else {
            return SUCCESS;
        }
    }
    //Date not past validation
    else if ("dateNotPast".equalsIgnoreCase(validationType)) {
        //if( ! past (value) )
        // return "date must not be in the past";
        //Current date
        Calendar c = Calendar.getInstance();
        //Input
        Calendar inputC = Calendar.getInstance();
        String yearParamStr, monthParamStr, dayParamStr;
        int yearDash = value.indexOf("-");
        int monthDash = value.lastIndexOf("-");
        if (yearDash != -1 && yearDash != monthDash) {
            yearParamStr = value.substring(0, yearDash);
            monthParamStr = value.substring(yearDash + 1, monthDash);
            dayParamStr = value.substring(monthDash + 1, value.length());
            inputC.set(Integer.parseInt(yearParamStr), Integer.parseInt(monthParamStr) - 1,
                    Integer.parseInt(dayParamStr));
            if (inputC.before(c)) {
                return this.DATE_NOT_PAST_MSG;
                //Returning null makes the error message "field is empty" display instead
                //return null;
            } else {
                return SUCCESS;
            }
        }
    }
    return null; //
}

From source file:org.kuali.ole.pdp.service.impl.PaymentFileValidationServiceImpl.java

/**
 * Checks the payment date is not more than 30 days past or 30 days coming
 * //from w ww  . j av  a 2 s  . c o m
 * @param paymentGroup <code>PaymentGroup</code> being checked
 * @param warnings <code>List</code> list of accumulated warning messages
 */
protected void checkGroupPaymentDate(PaymentGroup paymentGroup, List<String> warnings) {
    Timestamp now = dateTimeService.getCurrentTimestamp();

    Calendar nowPlus30 = Calendar.getInstance();
    nowPlus30.setTime(now);
    nowPlus30.add(Calendar.DATE, 30);

    Calendar nowMinus30 = Calendar.getInstance();
    nowMinus30.setTime(now);
    nowMinus30.add(Calendar.DATE, -30);

    if (paymentGroup.getPaymentDate() != null) {
        Calendar payDate = Calendar.getInstance();
        payDate.setTime(paymentGroup.getPaymentDate());

        if (payDate.before(nowMinus30)) {
            addWarningMessage(warnings, PdpKeyConstants.MESSAGE_PAYMENT_LOAD_PAYDATE_OVER_30_DAYS_PAST,
                    dateTimeService.toDateString(paymentGroup.getPaymentDate()));
        }

        if (payDate.after(nowPlus30)) {
            addWarningMessage(warnings, PdpKeyConstants.MESSAGE_PAYMENT_LOAD_PAYDATE_OVER_30_DAYS_OUT,
                    dateTimeService.toDateString(paymentGroup.getPaymentDate()));
        }
    } else {
        try {
            paymentGroup.setPaymentDate(dateTimeService.convertToSqlDate(now));
        } catch (ParseException e) {
            throw new RuntimeException("Unable to parse current timestamp into sql date " + e.getMessage());
        }
    }
}