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:nl.strohalm.cyclos.services.accountfees.AccountFeeServiceImpl.java

private BigDecimal calculateVolumeCharge(final MemberAccount account, final AccountFee volumeFee,
        final Period period, final BigDecimal additionalReserved, final boolean currentPeriod) {
    Calendar fromDate = period.getBegin();

    // Get the account status right after the last charged period
    AccountStatus status = accountService.getStatus(account, fromDate);

    // When there is some additional amount to consider as reserved, add it to the status
    status.setReservedAmount(status.getReservedAmount().add(additionalReserved));

    // Calculate the total days. We want the entire charged period. For example: if the fee was enabled in the middle of a month, it would be the
    // entire month. Likewise, if no end limit was given, the current period will be used (ie, and the last day in the current month)
    TimePeriod recurrence = volumeFee.getRecurrence();
    Period totalPeriod = recurrence.currentPeriod(period.getBegin());
    int totalDays = totalPeriod.getDays() + 1;

    // Calculate each difference, with the corresponding reserved amount
    Calendar lastDay = fromDate;/*  ww  w .j ava 2  s. c o  m*/
    Calendar lastChargedDay = fromDate;
    BigDecimal result = BigDecimal.ZERO;
    IteratorList<AccountDailyDifference> diffs = accountDao.iterateDailyDifferences(account, period);
    if (LOG.isDebugEnabled()) {
        LOG.debug("********************************");
        LOG.debug(FormatObject.formatObject(period.getBegin()) + "\t" + status.getBalance() + "\t"
                + status.getAvailableBalance());
    }
    try {
        if (diffs.hasNext()) {
            // There are differences - the lastChargedAvailable balance will be obtained within the loop
            for (AccountDailyDifference diff : diffs) {
                Calendar day = diff.getDay();
                int days = DateHelper.daysBetween(lastDay, day);
                // Get the available balance at that day
                BigDecimal available = status.getAvailableBalanceWithoutCreditLimit();
                if (volumeFee.getChargeMode().isNegative()) {
                    // If the charge is over negative amounts, consider the negated amount
                    available = available.negate();
                }
                // Take the free base into account
                if (volumeFee.getFreeBase() != null) {
                    available = available.subtract(volumeFee.getFreeBase());
                }
                // If the available balance was significant, calculate the charge
                if (available.compareTo(BigDecimal.ZERO) > 0) {
                    BigDecimal volume = new BigDecimal(available.doubleValue() * days / totalDays);
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(FormatObject.formatObject(day) + "\t" + diff.getBalance() + "\t"
                                + status.getAvailableBalanceWithoutCreditLimit().add(diff.getBalance()) + "\t"
                                + days + "\t" + totalDays + "\t" + volume);
                    }
                    BigDecimal toCharge = volume.multiply(volumeFee.getAmount())
                            .divide(BigDecimalHelper.ONE_HUNDRED);
                    // status.setReservedAmount(status.getReservedAmount().add(toCharge));
                    result = result.add(toCharge);
                    lastChargedDay = day;
                }
                lastDay = day;
                status.setBalance(status.getBalance().add(diff.getBalance()));
                status.setReservedAmount(status.getReservedAmount().add(diff.getReserved()));
            }
        }
    } finally {
        DataIteratorHelper.close(diffs);
    }

    Calendar toDate = period.getEnd();
    boolean lastPaymentInPeriodEnd = !toDate.before(lastChargedDay);
    LocalSettings settings = settingsService.getLocalSettings();

    // Only if the last payment was not today we have to take into account the results so far
    if (DateHelper.daysBetween(lastChargedDay, Calendar.getInstance()) != 0) {
        BigDecimal resultSoFar = settings.round(result);
        status.setReservedAmount(status.getReservedAmount().add(resultSoFar));
    }

    // Calculate the avaliable balance after the last diff, which will remain the same until the period end
    BigDecimal finalAvailableBalance = status.getAvailableBalanceWithoutCreditLimit();
    if (volumeFee.getChargeMode().isNegative()) {
        finalAvailableBalance = finalAvailableBalance.negate();
    }
    if (volumeFee.getFreeBase() != null) {
        finalAvailableBalance = finalAvailableBalance.subtract(volumeFee.getFreeBase());
    }

    // Consider the last time slice, between the last diff and the period end, if any
    if (lastPaymentInPeriodEnd && finalAvailableBalance.compareTo(BigDecimal.ZERO) > 0) {
        int days = DateHelper.daysBetween(lastChargedDay, toDate) + (currentPeriod ? 0 : 1);
        // Here, the lastChargedAvailableBalance is already subtracted from the free base (if any)
        BigDecimal volume = new BigDecimal(finalAvailableBalance.doubleValue() * days / totalDays);
        BigDecimal toCharge = volume.multiply(volumeFee.getAmount()).divide(BigDecimalHelper.ONE_HUNDRED);
        result = result.add(toCharge);
        if (LOG.isDebugEnabled()) {
            status.setReservedAmount(settings.round(status.getReservedAmount().add(toCharge)));
            LOG.debug(FormatObject.formatObject(lastChargedDay) + "\t0\t"
                    + status.getAvailableBalanceWithoutCreditLimit() + "\t" + days + "\t" + totalDays + "\t"
                    + volume);
        }
    }

    return settings.round(result);
}

From source file:org.apache.oozie.coord.CoordELFunctions.java

/**
 * Takes two offset times and returns a list of multiples of the frequency offset from the effective nominal time that occur
 * between them.  The caller should make sure that startCal is earlier than endCal.
 * <p>//w  w  w .  j  ava 2s  .  com
 * As a simple example, assume its the same day: startCal is 1:00, endCal is 2:00, frequency is 20min, and effective nominal
 * time is 1:20 -- then this method would return a list containing: -20, 0, 20, 40, 60
 *
 * @param startCal The earlier offset time
 * @param endCal The later offset time
 * @param eval The ELEvaluator to use; cannot be null
 * @return A list of multiple of the frequency offset from the effective nominal time that occur between the startCal and endCal
 */
public static List<Integer> expandOffsetTimes(Calendar startCal, Calendar endCal, ELEvaluator eval) {
    List<Integer> expandedFreqs = new ArrayList<Integer>();
    // Use eval because the "current" eval isn't set
    int freq = getDSFrequency(eval);
    TimeUnit freqUnit = getDSTimeUnit(eval);
    Calendar cal = getCurrentInstance(getActionCreationtime(eval), null, eval);
    int totalFreq = 0;
    if (startCal.before(cal)) {
        while (cal.after(startCal)) {
            cal.add(freqUnit.getCalendarUnit(), -freq);
            totalFreq += -freq;
        }
        if (cal.before(startCal)) {
            cal.add(freqUnit.getCalendarUnit(), freq);
            totalFreq += freq;
        }
    } else if (startCal.after(cal)) {
        while (cal.before(startCal)) {
            cal.add(freqUnit.getCalendarUnit(), freq);
            totalFreq += freq;
        }
    }
    // At this point, cal is the smallest multiple of the dataset frequency that is >= to the startCal and offset from the
    // effective nominal time.  Now we can find all of the instances that occur between startCal and endCal, inclusive.
    while (cal.before(endCal) || cal.equals(endCal)) {
        expandedFreqs.add(totalFreq);
        cal.add(freqUnit.getCalendarUnit(), freq);
        totalFreq += freq;
    }
    return expandedFreqs;
}

From source file:edu.eci.cosw.logica.Logica.java

/**
 * @obj verificar si una sala esta disponible e la fecha, con hora, especificada
 * @param fecha la fecha a revisar si hay disponibilidad
 * @param idSala identificador de la sala en donde se quiere verificar la disponiblidad
 * @param idEstablecimiento identificador del establecimeinto que que tiene la sala
 * @return true si la sala esta disponible en la fecha establecida, false de lo contrario
 *///from w w  w  .  j a  v a  2s.  c  o m
public boolean verificarDisponibilidadSala(Date fecha, Time hora, int idSala, int idEstablecimiento) {
    boolean res = true;
    Establecimiento e = re.findOne(idEstablecimiento);
    List<Sala> salas = consultarSalaPorEstablecimiento(e.getIdEstablecimiento());
    Sala s = null;

    for (int i = 0; i < salas.size(); i++) {
        if ((salas.get(i)).getIdSala() == idSala) {
            s = salas.get(i);
        }
    }
    try {
        List<Reservacion> reservas = consultarReservacionesPorSala(s.getIdSala());

        if (reservas != null) {
            Calendar c1 = new GregorianCalendar();
            Calendar c2 = new GregorianCalendar();
            c1.setTime(fecha);
            Time h1, h2;
            h1 = hora;
            boolean n = true;
            for (int i = 0; i < reservas.size() && n; i++) {
                h2 = reservas.get(i).getHora();
                c2.setTime(reservas.get(i).getFecha());

                if ((c1.after(c2) && h2.getHours() - h1.getHours() > 0)) {
                    n = true;
                } else if (c1.before(c2) && h1.getHours() - h2.getHours() > 0) {
                    n = true;
                } else {
                    n = false;
                    System.out.println(h1 + "                                      " + h2);
                }
            }
            if (n == false)
                res = false;
        } else {
            res = true;
        }
    } catch (NullPointerException npe) {
        res = true;
    }

    return res;
}

From source file:com.baidu.rigel.biplatform.tesseract.meta.impl.TimeDimensionMemberServiceImpl.java

/**
 * ???/*from   www . j  ava 2  s. c  o  m*/
 * 
 * @param level
 * @param parentMember
 * @return
 */
private List<MiniCubeMember> genMembersWithDayParentForAll(Level level, Member parentMember) {
    List<MiniCubeMember> members = Lists.newArrayList();
    Calendar calNow = Calendar.getInstance();
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.MONTH, Calendar.JANUARY);
    cal.set(Calendar.DAY_OF_MONTH, 1);
    SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
    while (cal.before(calNow) || (cal.compareTo(calNow) == 0)) {
        String day = sf.format(cal.getTime());
        MiniCubeMember dayMember = new MiniCubeMember(day);
        dayMember.setCaption(day);
        dayMember.setLevel(level);
        dayMember.setParent(parentMember);
        dayMember.setName(day);
        dayMember.setVisible(true);
        dayMember.getQueryNodes().add(day);
        members.add(dayMember);
        cal.add(Calendar.DATE, 1);
    }
    return members;
}

From source file:com.versobit.weatherdoge.WeatherUtil.java

private static String convertYahooCode(String code, String weatherTime, String sunrise, String sunset) {
    Date weatherDate = new Date();
    try {//  w ww.  j  av  a  2  s  . co m
        weatherDate = YAHOO_DATE_FORMAT.parse(weatherTime);
    } catch (ParseException ex) {
        Log.e(TAG, "Yahoo date format failed!", ex);
    }
    Calendar weatherCal = new GregorianCalendar();
    Calendar sunriseCal = new GregorianCalendar();
    Calendar sunsetCal = new GregorianCalendar();
    weatherCal.setTime(weatherDate);
    sunriseCal.setTime(weatherDate);
    sunsetCal.setTime(weatherDate);

    Matcher sunriseMatch = YAHOO_TIME.matcher(sunrise);
    Matcher sunsetMatch = YAHOO_TIME.matcher(sunset);
    if (!sunriseMatch.matches() || !sunsetMatch.matches()) {
        Log.e(TAG, "Failed to find sunrise/sunset. Using defaults.");
        sunriseMatch = YAHOO_TIME.matcher("6:00 am");
        sunsetMatch = YAHOO_TIME.matcher("6:00 pm");
        sunriseMatch.matches();
        sunsetMatch.matches();
    }
    // Set the sunrise to the correct hour and minute of the same day
    sunriseCal.set(Calendar.HOUR, Integer.parseInt(sunriseMatch.group(1)));
    sunriseCal.set(Calendar.MINUTE, Integer.parseInt(sunriseMatch.group(2)));
    sunriseCal.set(Calendar.SECOND, 0);
    sunriseCal.set(Calendar.MILLISECOND, 0);
    sunriseCal.set(Calendar.AM_PM, "am".equals(sunriseMatch.group(3)) ? Calendar.AM : Calendar.PM);

    // Set the sunset to the correct hour and minute of the same day
    sunsetCal.set(Calendar.HOUR, Integer.parseInt(sunsetMatch.group(1)));
    sunsetCal.set(Calendar.MINUTE, Integer.parseInt(sunsetMatch.group(2)));
    sunsetCal.set(Calendar.SECOND, 0);
    sunsetCal.set(Calendar.MILLISECOND, 0);
    sunsetCal.set(Calendar.AM_PM, "am".equals(sunsetMatch.group(3)) ? Calendar.AM : Calendar.PM);

    boolean isDaytime = true;
    if (weatherCal.before(sunriseCal) || weatherCal.after(sunsetCal)) {
        isDaytime = false;
    }

    String owmCode = "01";
    switch (Integer.parseInt(code)) {
    // Thunderstorms
    case 0:
    case 1:
    case 2:
    case 3:
    case 4:
    case 17:
    case 37:
    case 38:
    case 39:
    case 45:
    case 47:
        owmCode = "11";
        break;
    // Snow
    case 5:
    case 7:
    case 13:
    case 14:
    case 15:
    case 16:
    case 18:
    case 41:
    case 42:
    case 43:
    case 46:
        owmCode = "13";
        break;
    // Rain
    case 6:
    case 10:
    case 35:
        owmCode = "09";
        break;
    // Light-ish Rain
    case 8:
    case 9:
    case 11:
    case 12:
    case 40:
        owmCode = "10";
        break;
    // Fog
    case 19:
    case 20:
    case 21:
    case 22:
        owmCode = "50";
        break;
    // Cloudy
    case 27:
    case 28:
        owmCode = "04";
        break;
    // (Other) Cloudy
    case 26:
        owmCode = "03";
        break;
    // Partly Cloudy
    case 23:
    case 24:
    case 25:
    case 29:
    case 30:
    case 44:
        owmCode = "02";
        break;
    // Clear
    case 31:
    case 32:
    case 33:
    case 34:
    case 36:
        owmCode = "01";
        break;
    }
    return owmCode + (isDaytime ? "d" : "n");
}

From source file:com.kunze.androidlocaltodo.TaskListActivity.java

private void SetFriendlyDueDateText(TextView dueDateView, Calendar dueDate) {
    SimpleDateFormat dateFormatDisplay = new SimpleDateFormat("MM-dd-yyyy", Locale.US);
    Calendar now = Calendar.getInstance();
    int nowDay = TaskDatabase.ConvertDateToInt(now);
    int dueDay = TaskDatabase.ConvertDateToInt(dueDate);
    int dayDiff = nowDay - dueDay;
    if (dayDiff == 0) {
        dueDateView.setText("Today");
        dueDateView.setTextColor(Color.RED);
    } else if (dueDate.before(now)) {
        dueDateView.setText("+ " + dayDiff + " days!");
        dueDateView.setTextColor(Color.RED);
    } else if (dayDiff > -7) {
        dueDateView.setText(dueDate.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.US));
        dueDateView.setTextColor(Color.BLACK);
    } else if (dayDiff > -14) {
        dueDateView.setText("Next " + dueDate.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.US));
        dueDateView.setTextColor(Color.BLACK);
    } else {/*w  w  w .j a v a2 s. co  m*/
        dueDateView.setText(dateFormatDisplay.format(dueDate.getTime()));
        dueDateView.setTextColor(Color.BLACK);
    }
}

From source file:org.kuali.kfs.module.tem.service.impl.PerDiemServiceImpl.java

/**
 * Determines if:/* w ww  .j av  a2  s.c o m*/
 * <ul>
 * <li>A current mileage rate for the KFS-TEM / Document / PER_DIEM_MILEAGE_RATE_EXPENSE_TYPE_CODE is available; if it is not, then per diem cannot be created
 * </ul>
 * @param form the form with the document on it, which may help in making such a decision
 */
@Override
public boolean isMileageRateAvailableForAllPerDiem(TravelDocument doc) {
    final String defaultPerDiemMileageRate = getDefaultPerDiemMileageRateExpenseType();
    if (StringUtils.isBlank(defaultPerDiemMileageRate)) {
        return false;
    }
    if (StringUtils.isBlank(doc.getTripTypeCode()) || doc.getTripBegin() == null || doc.getTripEnd() == null) {
        return true; // we can't create per diem when trip begin or end are blank anyhow - but we shouldn't get the error
    }
    // now we need to loop through each day from begin date to end date to see if there is a validate mileage rate record for it
    Calendar currDay = Calendar.getInstance();
    currDay.setTime(KfsDateUtils.clearTimeFields(doc.getTripBegin()));
    Calendar lastDay = Calendar.getInstance();
    lastDay.setTime(KfsDateUtils.clearTimeFields(doc.getTripEnd()));

    while (currDay.before(lastDay) || currDay.equals(lastDay)) {
        java.sql.Date effectiveDay = doc
                .getEffectiveDateForPerDiem(new java.sql.Timestamp(currDay.getTimeInMillis()));
        final MileageRate currDayMileageRate = getMileageRateService()
                .findMileageRateByExpenseTypeCodeAndDate(defaultPerDiemMileageRate, effectiveDay);
        if (currDayMileageRate == null) {
            return false;
        }
        currDay.add(Calendar.DATE, 1);
    }
    // we're good
    return true;
}

From source file:com.njlabs.amrita.aid.info.Calender.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private void setCustomResourceForDates() {

    final Handler dataHandler = new Handler();
    (new Thread(new Runnable() {
        @Override//from w  w w.  java 2  s . c  om
        public void run() {

            try {

                InputStream icsInput = getAssets().open("ASECalendar.ics");
                CalendarBuilder builder = new CalendarBuilder();
                net.fortuna.ical4j.model.Calendar calendar = builder.build(icsInput);

                for (Object calendarComponentObject : calendar.getComponents()) {
                    CalendarComponent calendarComponent = (CalendarComponent) calendarComponentObject;
                    String title = calendarComponent.getProperty(Property.SUMMARY).getValue();
                    if (title.length() > 4) {
                        Date startDate = parseDate(calendarComponent.getProperty(Property.DTSTART).getValue());
                        Date endDate = parseDate(calendarComponent.getProperty(Property.DTEND).getValue());
                        title = title.replaceAll("^CD\\d\\d:\\s", "").replaceAll("^CD\\d:\\s", "").replace("*",
                                "");

                        int color = R.color.calendar_green;

                        if (containsAny(title,
                                new String[] { "assessment", "exam", "test", "assesment", "end semester" })) {
                            color = R.color.calendar_red;
                        } else if (containsAny(title,
                                new String[] { "institution day", "amritotsavam", "amritotasavam", "classes",
                                        "working", "instruction", "enrolment", "Birthday", "Talent", "TABLE",
                                        "orientation", "counselling" })) {
                            color = R.color.calendar_blue;
                        } else if (containsAny(title, new String[] { "anokha", "tech fest" })) {
                            color = R.color.calendar_anokha_orange;
                        }

                        Calendar start = Calendar.getInstance();
                        start.setTime(startDate);
                        Calendar end = Calendar.getInstance();
                        end.setTime(endDate);

                        //noinspection WrongConstant
                        if (start.get(Calendar.DAY_OF_MONTH) == end.get(Calendar.DAY_OF_MONTH)
                                || end.get(Calendar.DAY_OF_MONTH) == start.get(Calendar.DAY_OF_MONTH) + 1) {
                            backgroundColors.put(startDate, color);
                            textColors.put(startDate, R.color.white);
                            descriptions.put(formatter.format(startDate), title);
                        } else {
                            for (Date date = start.getTime(); start.before(end); start.add(Calendar.DATE,
                                    1), date = start.getTime()) {
                                backgroundColors.put(date, color);
                                textColors.put(date, R.color.white);
                                descriptions.put(formatter.format(date), title);
                            }
                        }
                    }
                }

            } catch (Exception e) {
                FirebaseCrash.report(e);
            }

            dataHandler.post(new Runnable() {
                @Override
                public void run() {
                    if (caldroidFragment != null) {
                        caldroidFragment.setBackgroundResourceForDates(backgroundColors);
                        caldroidFragment.setTextColorForDates(textColors);
                        caldroidFragment.refreshView();
                        findViewById(R.id.calendar_holder).setVisibility(View.VISIBLE);
                        findViewById(R.id.progress).setVisibility(View.GONE);
                    }
                }
            });
        }
    })).start();
}

From source file:org.openmrs.module.lancearmstrong.LafServiceImpl.java

/**
  * Match a target date with a completed date based on 7-day-proximity rule
  * /*from   www.jav a 2  s.  co  m*/
  * @param targetDate
  * @param lastCompleted
  * @return
  */
private boolean matchCompletedDate(Date targetDate, Date lastCompleted) {
    // TODO Auto-generated method stub
    Calendar calTarget1 = Calendar.getInstance();
    calTarget1.setTime(targetDate);
    calTarget1.add(Calendar.DATE, MATCH_DAYS);
    Calendar calTarget2 = Calendar.getInstance();
    calTarget2.setTime(targetDate);
    calTarget2.add(Calendar.DATE, -MATCH_DAYS);

    Calendar calCompl = Calendar.getInstance();
    calCompl.setTime(lastCompleted);

    if (calCompl.before(calTarget1) && calCompl.after(calTarget2)) {
        return true;
    }
    return false;
}

From source file:com.alibaba.otter.manager.biz.monitor.impl.AbstractRuleMonitor.java

protected boolean isAfter(Calendar now, String time) {
    String[] hourAndMin = StringUtils.split(time, ":");
    if (hourAndMin == null || hourAndMin.length != 2) {
        log.error("error period time format in rule : " + time);
        return isInPeriodWhenErrorFormat();
    }//from w  w w  .  java  2s.  c o m

    int hour;
    int min;
    try {
        hour = Integer.parseInt(hourAndMin[0]);
        min = Integer.parseInt(hourAndMin[1]);
    } catch (NumberFormatException e) {
        log.error("error period time format in rule : " + time, e);
        return isInPeriodWhenErrorFormat();
    }

    if (hour > 24 || min > 60) {
        log.error("error period time format in rule : " + time);
        return isInPeriodWhenErrorFormat();
    }

    Calendar when = (Calendar) now.clone();
    when.set(Calendar.HOUR_OF_DAY, hour);
    when.set(Calendar.MINUTE, min);

    return !now.before(when);
}