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:com.devnexus.ting.web.controller.admin.RegistrationController.java

private String[] formatTicketTypes(EventSignup signUp) {
    return signUp.getGroups().stream().filter((TicketGroup group) -> {
        Calendar today = Calendar.getInstance();
        return today.after(toCal(group.getOpenDate())) && today.before(toCal(group.getCloseDate()));
    }).map((TicketGroup group) -> {/*from ww  w . j  ava2 s.c om*/
        return String.format("%s -|-%d\\n", group.getLabel(), group.getId());
    }).toArray(String[]::new);
}

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

protected boolean isBefore(DateDisplayTypes displayType, Date date1, Date date2) {
    Calendar cal1 = Calendar.getInstance();
    cal1.setTime(date1);/*from  w w w  .  ja  va2  s  .c  o m*/
    Calendar cal2 = Calendar.getInstance();
    cal2.setTime(date2);
    if (cal2.before(cal1)) {
        return false;
    }
    // i really feel like there should be a cleaner way to do this but it
    // escapes me
    if (cal1.get(Calendar.YEAR) < cal2.get(Calendar.YEAR)) {
        return true;
    } else if (cal1.get(Calendar.YEAR) > cal2.get(Calendar.YEAR) || displayType == DateDisplayTypes.Yearly) {
        return false;
    }
    // we know the years are the same and we're comparing less than years
    if (cal1.get(Calendar.MONTH) < cal2.get(Calendar.MONTH)) {
        return true;
    } else if (cal1.get(Calendar.MONTH) > cal2.get(Calendar.MONTH) || displayType == DateDisplayTypes.Monthly) {
        return false;
    }
    // we know months and years are the same and we're comparing less than
    // months
    if (cal1.get(Calendar.WEEK_OF_YEAR) < cal2.get(Calendar.WEEK_OF_YEAR)) {
        return true;
    } else if (cal1.get(Calendar.WEEK_OF_YEAR) > cal2.get(Calendar.WEEK_OF_YEAR)
            || displayType == DateDisplayTypes.Weekly) {
        return false;
    }
    // we know months, years, and weeks are the same and we're comparing
    // less than weeks
    if (cal1.get(Calendar.DATE) < cal2.get(Calendar.DATE)) {
        return true;
    } else if (cal1.get(Calendar.DATE) > cal2.get(Calendar.DATE) || displayType == DateDisplayTypes.Daily) {
        return false;
    }
    // we know months, years,weeks, and days are the same and we're
    // comparing less than days
    if (cal1.get(Calendar.HOUR) < cal2.get(Calendar.HOUR)) {
        return true;
    }
    // anything else is not before
    return false;
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.publico.RoomSiteViewerDispatchAction.java

public ActionForward roomViewer(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    User userView = getUserView(request);

    String roomName = request.getParameter("roomName");
    if (roomName == null) {
        roomName = (String) request.getAttribute("roomName");
    }/* w w w .  j ava  2  s . c  o m*/
    request.setAttribute("roomName", roomName);
    RoomKey roomKey = null;

    if (roomName != null) {
        roomKey = new RoomKey(roomName);

        ISiteComponent bodyComponent = new InfoSiteRoomTimeTable();
        DynaActionForm indexForm = (DynaActionForm) form;
        Integer indexWeek = (Integer) indexForm.get("indexWeek");
        // Integer executionPeriodID = (Integer)
        // indexForm.get("selectedExecutionPeriodID");
        String executionPeriodIDString = request.getParameter("selectedExecutionPeriodID");
        if (executionPeriodIDString == null) {
            executionPeriodIDString = (String) request.getAttribute("selectedExecutionPeriodID");
        }
        String executionPeriodID = (executionPeriodIDString != null) ? executionPeriodIDString : null;
        if (executionPeriodID == null) {
            try {
                // executionPeriodID = (Integer)
                // indexForm.get("selectedExecutionPeriodID");
                executionPeriodID = indexForm.get("selectedExecutionPeriodID").equals("") ? null
                        : (String) indexForm.get("selectedExecutionPeriodID");
            } catch (IllegalArgumentException ex) {
            }
        }
        Calendar today = new DateMidnight().toCalendar(null);
        ArrayList weeks = new ArrayList();

        InfoExecutionPeriod executionPeriod;
        if (executionPeriodID == null) {
            executionPeriod = ReadCurrentExecutionPeriod.run();
            executionPeriodID = executionPeriod.getExternalId();
            try {
                indexForm.set("selectedExecutionPeriodID", executionPeriod.getExternalId().toString());
            } catch (IllegalArgumentException ex) {
            }
        } else {
            executionPeriod = ReadExecutionPeriodByOID.run(executionPeriodID);
        }

        // weeks
        Calendar begin = Calendar.getInstance();
        begin.setTime(executionPeriod.getBeginDate());
        Calendar end = Calendar.getInstance();
        end.setTime(executionPeriod.getEndDate());
        ArrayList weeksLabelValueList = new ArrayList();
        begin.add(Calendar.DATE, Calendar.MONDAY - begin.get(Calendar.DAY_OF_WEEK));
        int i = 0;
        boolean selectedWeek = false;
        while (begin.before(end) || begin.before(Calendar.getInstance())) {
            Calendar day = Calendar.getInstance();
            day.setTimeInMillis(begin.getTimeInMillis());
            weeks.add(day);
            String beginWeekString = DateFormatUtils.format(begin.getTime(), "dd/MM/yyyy");
            begin.add(Calendar.DATE, 5);
            String endWeekString = DateFormatUtils.format(begin.getTime(), "dd/MM/yyyy");
            weeksLabelValueList.add(
                    new LabelValueBean(beginWeekString + " - " + endWeekString, new Integer(i).toString()));
            begin.add(Calendar.DATE, 2);
            if (!selectedWeek && indexWeek == null && Calendar.getInstance().before(begin)) {
                indexForm.set("indexWeek", new Integer(i));
                selectedWeek = true;
            }
            i++;
        }

        final Collection<ExecutionSemester> executionSemesters = rootDomainObject.getExecutionPeriodsSet();
        final List<LabelValueBean> executionPeriodLabelValueBeans = new ArrayList<LabelValueBean>();
        for (final ExecutionSemester ep : executionSemesters) {
            if (ep.getState().equals(PeriodState.OPEN) || ep.getState().equals(PeriodState.CURRENT)) {
                executionPeriodLabelValueBeans.add(new LabelValueBean(
                        ep.getName() + " " + ep.getExecutionYear().getYear(), ep.getExternalId().toString()));
            }
        }
        request.setAttribute(PresentationConstants.LABELLIST_EXECUTIONPERIOD, executionPeriodLabelValueBeans);

        request.setAttribute(PresentationConstants.LABELLIST_WEEKS, weeksLabelValueList);
        if (indexWeek != null) {
            final int xpto = indexWeek.intValue();
            if (xpto < weeks.size()) {
                today = (Calendar) weeks.get(xpto);
            } else {
                today = (Calendar) weeks.iterator().next();
                indexForm.set("indexWeek", new Integer(0));
            }
        }

        try {
            SiteView siteView = (SiteView) RoomSiteComponentServiceByExecutionPeriodID.run(bodyComponent,
                    roomKey, today, executionPeriodID);

            request.setAttribute("siteView", siteView);

        } catch (NonExistingServiceException e) {
            throw new NonExistingActionException(e);
        } catch (FenixServiceException e) {
            throw new FenixActionException(e);
        }
        return mapping.findForward("roomViewer");
    }
    throw new FenixActionException();

}

From source file:org.apache.synapse.mediators.deprecation.DeprecationMediator.java

private boolean isDeprecated(SynapseObject service) {

    try {/*from   w  w  w.  j  av  a2  s.c om*/
        if (service.getBoolean("enabled").booleanValue()) {
            Calendar current = Calendar.getInstance();
            TimeZone tz = current.getTimeZone();
            int offset = tz.getRawOffset();
            Calendar calendar = new GregorianCalendar(tz);

            DateFormat df = new SimpleDateFormat("d/M/y:H:m");
            df.setTimeZone(tz);
            Date d1 = service.getDate(DeprecationConstants.CFG_DEPRECATION_FROM_DATE);
            Calendar fromCalendar = new GregorianCalendar(tz);
            d1.setTime(d1.getTime() + offset);
            fromCalendar.setTime(d1);
            String toDate = service.getDate(DeprecationConstants.CFG_DEPRECATION_TO_DATE).toString();
            if (toDate == null || (toDate.length() == 0)) {
                return calendar.before(fromCalendar);
            }

            Date d2 = service.getDate("toDate");
            Calendar toCalendar = new GregorianCalendar(tz);
            d2.setTime(d2.getTime() + offset);
            toCalendar.setTime(d2);
            return (calendar.after(fromCalendar) && calendar.before(toCalendar));
        }
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return false;
}

From source file:org.openmrs.module.rwandareports.dataset.evaluator.HIVARTRegisterDataSetDefinition2Evaluator.java

private String retrieveCorrectMonthsOb(int month, List<DrugOrder> orders, Date startingDate) {
    String drugOrders = "";

    if (startingDate != null) {
        Calendar monthDate = Calendar.getInstance();
        monthDate.setTime(startingDate);
        monthDate.add(Calendar.MONTH, month);

        Calendar currentDate = Calendar.getInstance();

        if (monthDate.before(currentDate)) {

            for (DrugOrder current : orders) {
                if (current.isCurrent(monthDate.getTime())) {
                    String drugName = "Drug Missing";
                    try {
                        drugName = current.getDrug().getName();
                    } catch (Exception e) {
                        System.err.println(e.getMessage());
                    }//from  www  . j  a  v  a 2s . c om

                    if (drugOrders.length() > 0) {
                        drugOrders = drugOrders + "," + drugName;
                    } else {
                        drugOrders = drugName;
                    }
                }
            }
        }

        if (drugOrders.length() > 0) {
            drugOrders = drugOrders + " " + new SimpleDateFormat("MMM yyyy").format(monthDate.getTime());
        }
    }
    return drugOrders;
}

From source file:com.square.core.util.validation.ValidationExpressionUtil.java

/**
 * Dtermine si la date de naissance passe en paramtre est valide ou pas.
 * @param dateDeNaissance la date de naissance  vrifier
 * @return true si la date est valide, false sinon
 *///w w w .  jav a  2 s .  c o  m
public boolean isDateDeNaissanceValide(Calendar dateDeNaissance) {
    Calendar dateLimiteValidite = Calendar.getInstance();
    dateLimiteValidite.add(Calendar.MONTH, 9);
    dateLimiteValidite = DateUtils.truncate(dateLimiteValidite, Calendar.DAY_OF_MONTH);
    final Calendar dateNaissanceMois = DateUtils.truncate(dateDeNaissance, Calendar.DAY_OF_MONTH);
    boolean isDateDeNaissanceValide = false;
    // On vrifie que la date de naissance est antrieure  la date courante + 9 mois pour autoriser la date de naissance d'un futur nouveau n
    if (dateDeNaissance != null
            && (dateNaissanceMois.before(dateLimiteValidite) || dateNaissanceMois.equals(dateLimiteValidite))) {
        isDateDeNaissanceValide = true;
    }
    return isDateDeNaissanceValide;
}

From source file:org.openmrs.module.rwandareports.dataset.evaluator.HIVARTRegisterDataSetDefinitionEvaluator.java

private String retrieveCorrectMonthsOb(int month, List<DrugOrder> orders, Date startingDate) {
    String drugOrders = "";

    if (startingDate != null) {
        Calendar monthDate = Calendar.getInstance();
        monthDate.setTime(startingDate);
        monthDate.add(Calendar.MONTH, month);

        Calendar currentDate = Calendar.getInstance();

        if (monthDate.before(currentDate)) {

            for (DrugOrder current : orders) {
                if (current.isCurrent(monthDate.getTime())) {
                    String drugName = "Drug Missing";
                    try {
                        drugName = current.getDrug().getName();
                    } catch (Exception e) {
                        System.err.println(e.getMessage());
                    }/*from  www  . j a v a2s.c o  m*/

                    if (drugOrders.length() > 0) {
                        drugOrders = drugOrders + "," + drugName;
                    } else {
                        drugOrders = drugName;
                    }
                }
            }
        }

        if (drugOrders.length() > 0) {
            drugOrders = drugOrders + ";" + new SimpleDateFormat("MMM yyyy").format(monthDate.getTime());
        }
    }
    return drugOrders;
}

From source file:nl.strohalm.cyclos.services.transactions.ScheduledPaymentServiceImpl.java

private void recoverScheduledPayments() {

    // Find whether we are executing less than one hour before the scheduled tasks run.
    // If yes, consider today as deadline. Otherwise, today the scheduled task will yet run,
    // so, consider yesterday as deadline.
    final LocalSettings localSettings = settingsService.getLocalSettings();
    final Calendar now = Calendar.getInstance();
    final Calendar limit = DateHelper.truncate(now);
    limit.set(Calendar.HOUR_OF_DAY, localSettings.getSchedulingHour());
    limit.add(Calendar.HOUR_OF_DAY, -1);
    limit.set(Calendar.MINUTE, localSettings.getSchedulingMinute());
    Calendar time;/*from w  w w  .j a va2 s  . c om*/
    if (now.before(limit)) {
        time = DateHelper.truncatePreviosDay(now);
    } else {
        time = DateHelper.truncate(now);
    }

    paymentService.processScheduled(Period.endingAt(time));
}

From source file:com.virtusa.akura.student.controller.StudentAttendenceController.java

/**
 * get all days without special holidays and Saturday,Sunday for given Date range. map key contains date
 * and value contains AttendeceStatus object with default values(as absent day)
 * /*from  w w w .  j  av a2 s.  co m*/
 * @param from from date
 * @param to to date
 * @return map
 * @throws AkuraAppException when exception occurs
 */
private Map<String, AttendeceStatus> getDaysWithoutHolydays(Date from, Date to) throws AkuraAppException {

    Calendar calFrom = Calendar.getInstance();
    Calendar calTo = Calendar.getInstance();

    calFrom.setTime(from);
    calTo.setTime(to);

    List<Holiday> holidayList = commonService.findHolidayByYear(from, to);

    Map<String, AttendeceStatus> allDaysBetween = new TreeMap<String, AttendeceStatus>();

    // to get name ex Sunday ,Monday ..
    DateFormatSymbols symbols = new DateFormatSymbols();
    String[] weekDays = symbols.getWeekdays();

    while (calFrom.before(calTo) || calFrom.equals(calTo)) {

        int dyaOfWeek = calFrom.get(Calendar.DAY_OF_WEEK);
        // remove weekends and special holidays
        if (dyaOfWeek != Calendar.SATURDAY && dyaOfWeek != Calendar.SUNDAY
                && !DateUtil.isHoliday(holidayList, calFrom.getTime())) {

            AttendeceStatus attSttus = new AttendeceStatus();
            attSttus.setDay(weekDays[dyaOfWeek]);
            allDaysBetween.put(DateUtil.getFormatDate(calFrom.getTime()), attSttus);
        }

        calFrom.set(Calendar.DATE, calFrom.get(Calendar.DATE) + 1);
    }

    return allDaysBetween;
}

From source file:rapture.kernel.RunnerApiImpl.java

/**
 * Remove old status records from this, then save if anything changed
 *///w  w  w  .j av a2s  .  co  m
@Override
public void cleanRunnerStatus(CallingContext context, int ageInMinutes) {
    List<String> runnerServers = getRunnerServers(context);
    for (String serverName : runnerServers) {
        String lockName = getRunnerStatusLockName(serverName);
        LockHandle lockHandle = acquireLock(context, lockName);
        if (lockHandle != null) {
            try {
                logger.debug("Cleaning data on server " + serverName);
                RaptureRunnerStatus status = getRunnerStatus(context, serverName);
                List<String> toRemove = new ArrayList<>();
                Calendar now = Calendar.getInstance();
                now.add(Calendar.MINUTE, ageInMinutes * -1);
                for (Map.Entry<String, RaptureRunnerInstanceStatus> entry : status.getStatusByInstanceName()
                        .entrySet()) {
                    Calendar entryDate = Calendar.getInstance();
                    entryDate.setTime(entry.getValue().getLastSeen());
                    if (entryDate.before(now)) {
                        toRemove.add(entry.getKey());
                    }
                }
                if (!toRemove.isEmpty()) {
                    for (String instance : toRemove) {
                        status.getStatusByInstanceName().remove(instance);
                    }
                    if (!status.getStatusByInstanceName().isEmpty()) {
                        RaptureRunnerStatusStorage.add(status, context.getUser(), "Clear runner status");
                    } else {
                        RaptureRunnerStatusStorage.deleteByFields(serverName, context.getUser(),
                                "Clear runner status");
                    }
                }
            } finally {
                logger.debug("Done cleaning data on server " + serverName);
                releaseLock(context, lockName, lockHandle);
            }
        } else {
            logger.info(String.format(
                    "Unable to acquire lock %s, so unable to clean runner status for server %s this time",
                    lockName, serverName));
        }
    }
}