Example usage for java.util Calendar after

List of usage examples for java.util Calendar after

Introduction

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

Prototype

public boolean after(Object when) 

Source Link

Document

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

Usage

From source file:org.kuali.coeus.propdev.impl.print.ProposalBaseStream.java

/**
 *
 * This method computes the number of months between any 2 given {@link java.sql.Date} objects
 *
 * @param dateStart starting date./*from ww  w .  j av a 2 s.  c om*/
 * @param dateEnd end date.
 *
 * @return number of months between the start date and end date.
 */
public ScaleTwoDecimal getNumberOfMonths(Date dateStart, Date dateEnd) {
    ScaleTwoDecimal monthCount = ScaleTwoDecimal.ZERO;
    int fullMonthCount = 0;

    Calendar startDate = Calendar.getInstance();
    Calendar endDate = Calendar.getInstance();
    startDate.setTime(dateStart);
    endDate.setTime(dateEnd);

    startDate.clear(Calendar.HOUR);
    startDate.clear(Calendar.MINUTE);
    startDate.clear(Calendar.SECOND);
    startDate.clear(Calendar.MILLISECOND);

    endDate.clear(Calendar.HOUR);
    endDate.clear(Calendar.MINUTE);
    endDate.clear(Calendar.SECOND);
    endDate.clear(Calendar.MILLISECOND);

    if (startDate.after(endDate)) {
        return ScaleTwoDecimal.ZERO;
    }
    int startMonthDays = startDate.getActualMaximum(Calendar.DATE) - startDate.get(Calendar.DATE);
    startMonthDays++;
    int startMonthMaxDays = startDate.getActualMaximum(Calendar.DATE);
    BigDecimal startMonthFraction = BigDecimal.valueOf(startMonthDays).setScale(2, RoundingMode.HALF_UP).divide(
            BigDecimal.valueOf(startMonthMaxDays).setScale(2, RoundingMode.HALF_UP), RoundingMode.HALF_UP);

    int endMonthDays = endDate.get(Calendar.DATE);
    int endMonthMaxDays = endDate.getActualMaximum(Calendar.DATE);

    BigDecimal endMonthFraction = BigDecimal.valueOf(endMonthDays).setScale(2, RoundingMode.HALF_UP).divide(
            BigDecimal.valueOf(endMonthMaxDays).setScale(2, RoundingMode.HALF_UP), RoundingMode.HALF_UP);

    startDate.set(Calendar.DATE, 1);
    endDate.set(Calendar.DATE, 1);

    while (startDate.getTimeInMillis() < endDate.getTimeInMillis()) {
        startDate.set(Calendar.MONTH, startDate.get(Calendar.MONTH) + 1);
        fullMonthCount++;
    }
    fullMonthCount = fullMonthCount - 1;
    monthCount = monthCount.add(new ScaleTwoDecimal(fullMonthCount))
            .add(new ScaleTwoDecimal(startMonthFraction)).add(new ScaleTwoDecimal(endMonthFraction));
    return monthCount;
}

From source file:de.hybris.platform.acceleratorservices.web.payment.validation.SopPaymentDetailsValidator.java

@Override
public void validate(final Object object, final Errors errors) {
    final SopPaymentDetailsForm form = (SopPaymentDetailsForm) object;

    final Calendar startOfCurrentMonth = getCalendarResetTime();
    startOfCurrentMonth.set(Calendar.DAY_OF_MONTH, 1);

    final Calendar startOfNextMonth = getCalendarResetTime();
    startOfNextMonth.set(Calendar.DAY_OF_MONTH, 1);
    startOfNextMonth.add(Calendar.MONTH, 1);

    final Calendar start = parseDate(form.getCard_startMonth(), form.getCard_startYear());
    final Calendar expiration = parseDate(form.getCard_expirationMonth(), form.getCard_expirationYear());

    if (start != null && !start.before(startOfNextMonth)) {
        errors.rejectValue("card_startMonth", "payment.startDate.invalid");
    }// w w  w  .j  av  a  2 s  .  c om
    if (expiration != null && expiration.before(startOfCurrentMonth)) {
        errors.rejectValue("card_expirationMonth", "payment.startDate.invalid");
    }
    if (start != null && expiration != null && start.after(expiration)) {
        errors.rejectValue("card_startMonth", "payment.startDate.invalid");
    }

    if (StringUtils.isBlank(form.getBillTo_country())) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "billTo_country", "address.country.invalid");
    } else {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "billTo_firstName", "address.firstName.invalid");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "billTo_lastName", "address.lastName.invalid");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "billTo_street1", "address.line1.invalid");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "billTo_city", "address.city.invalid");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "billTo_postalCode", "address.postcode.invalid");
    }
}

From source file:com.nagarro.core.validator.PaymentDetailsDTOValidator.java

@Override
public void validate(final Object target, final Errors errors) {
    final PaymentDetailsWsDTO paymentDetails = (PaymentDetailsWsDTO) target;

    if (StringUtils.isNotBlank(paymentDetails.getStartMonth())
            && StringUtils.isNotBlank(paymentDetails.getStartYear())
            && StringUtils.isNotBlank(paymentDetails.getExpiryMonth())
            && StringUtils.isNotBlank(paymentDetails.getExpiryYear())) {
        final Calendar start = Calendar.getInstance();
        start.set(Calendar.DAY_OF_MONTH, 0);
        start.set(Calendar.MONTH, Integer.parseInt(paymentDetails.getStartMonth()) - 1);
        start.set(Calendar.YEAR, Integer.parseInt(paymentDetails.getStartYear()) - 1);

        final Calendar expiration = Calendar.getInstance();
        expiration.set(Calendar.DAY_OF_MONTH, 0);
        expiration.set(Calendar.MONTH, Integer.parseInt(paymentDetails.getExpiryMonth()) - 1);
        expiration.set(Calendar.YEAR, Integer.parseInt(paymentDetails.getExpiryYear()) - 1);

        if (start.after(expiration)) {
            errors.rejectValue("startMonth", "payment.startDate.invalid");
        }//from   ww w . j  a v a  2 s .  c  o m
    }

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "accountHolderName", "field.required");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "cardType.code", "field.required");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "cardNumber", "field.required");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "expiryMonth", "field.required");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "expiryYear", "field.required");

    paymentAddressValidator.validate(paymentDetails, errors);
}

From source file:com.virtusa.akura.student.delegate.StudentLoginDelegate.java

/**
 * method to calculate attendance average.
 * /*from w ww . j av a2s .c o m*/
 * @param studentId - integer
 * @return average in double. * @param year - Date
 * @throws AkuraAppException when exception occurs
 * @return attendance average in double.
 */
private double calculateAttendance(int studentId, Date year) throws AkuraAppException {

    Student student = studentService.findStudent(studentId);

    String strStartDate = "";

    String strEndDate = DateUtil.getStringYear(year) + END_YEAR;

    Calendar firstDayCalendar = Calendar.getInstance();
    firstDayCalendar.setTime(student.getFirstSchoolDay());
    String firstDayYear = Integer.toString(firstDayCalendar.get(Calendar.YEAR));
    boolean checkFirstday = false;

    if (firstDayYear.equals(DateUtil.getStringYear(year))) {
        strStartDate = DateUtil.getFormatDate(student.getFirstSchoolDay());
        checkFirstday = true;
    } else {
        strStartDate = DateUtil.getStringYear(year) + START_YEAR;
    }

    List<Holiday> holidayList = commonService.findHolidayByYear(DateUtil.getParseDate(strStartDate),
            DateUtil.getParseDate(strEndDate));
    Calendar calendar = Calendar.getInstance();
    Date dateTo = calendar.getTime();
    dateTo = DateUtil.getParseDate(DateUtil.getFormatDate(dateTo));
    Date dateFrom = DateUtil.getParseDate(strStartDate);
    dateFrom = DateUtil.getParseDate(DateUtil.getFormatDate(dateFrom));
    Calendar fromDate = Calendar.getInstance();
    fromDate.setTime(dateFrom);

    Calendar toDate = Calendar.getInstance();
    toDate.setTime(dateTo);
    int holidayCount = HolidayUtil.countHolidays(fromDate, toDate, holidayList);
    fromDate.setTime(dateFrom);
    int numberOfDays = 0;

    if (checkFirstday) {
        if (!fromDate.after(toDate)) {
            int dayCount = toDate.get(Calendar.DAY_OF_YEAR) - fromDate.get(Calendar.DAY_OF_YEAR);
            numberOfDays = dayCount - holidayCount;
        }

    } else {

        numberOfDays = calendar.get(Calendar.DAY_OF_YEAR) - holidayCount;
    }

    numberOfDays++;
    int numbeeOfPresentDays = dailyAttendanceService.getAttendanceBettween(studentId, dateFrom, dateTo).size();

    double presentDays = (double) numbeeOfPresentDays / numberOfDays;

    return presentDays * HUNDRED;

}

From source file:com.nridge.core.base.field.FieldRange.java

/**
 * Return <i>true</i> if the calendar instance is within the
 * defined range of values or <i>false</i> otherwise.
 *
 * @param aValue Calendar instance.//from  ww  w. j av  a2s.  com
 *
 * @return <i>true</i> or <i>false</i>
 */
public boolean isValid(Calendar aValue) {
    return ((aValue.after(mMinCalendar)) && (aValue.before(mMaxCalendar)));
}

From source file:gov.nih.nci.cabig.caaers.domain.DateTimeValue.java

/**
 * Check if date is in valid./*w  w  w .  j a  v a 2s .com*/
 *
 * @return true, if successful
 */
public boolean checkIfDateIsInValid() {

    Calendar now = Calendar.getInstance();

    return (this.getMonth() != null && (this.getMonth() < 0 || this.getMonth() > 12))
            || (this.getDay() != null && (this.getDay() < 0 || this.getDay() > 31))
            || (this.getYear() == null || this.getYear() < 1900 || this.getYear() > now.get(Calendar.YEAR))
            || now.after(this.toDate());
}

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

public void editEndTime(boolean alarmToday, AlarmSchedule alarmSchedule) {
    int UID = alarmSchedule.getUID();
    Calendar endTime = alarmSchedule.getEndTime();
    scheduleDatabaseAdapter.updateEndTime(UID, Utils.calendarToTimeString(endTime));
    if (alarmToday && alarmSchedule.getActivated()) {
        Calendar startTime = alarmSchedule.getStartTime();
        Calendar rightNow = Calendar.getInstance();
        FixedAlarmSchedule fixedAlarmSchedule = new FixedAlarmSchedule(alarmSchedule);
        if (endTime.after(rightNow) && startTime.before(rightNow)) {
            ScheduledRepeatingAlarm scheduledRepeatingAlarm = new ScheduledRepeatingAlarm(mContext,
                    fixedAlarmSchedule);
            scheduledRepeatingAlarm.updateAlarm();
            //Update cancels the original alarm, so image needs to be set again
            Utils.setImageStatus(mContext, Constants.SCHEDULE_RUNNING);
        } else {/*w ww.j av  a 2 s. c  om*/
            if (UID == Utils.getRunningScheduledAlarm(mContext)) {
                new ScheduledRepeatingAlarm(mContext, fixedAlarmSchedule).cancelAlarm();
            }
        }
    }
}

From source file:org.kuali.kra.coi.service.impl.CoiMessagesServiceImpl.java

/**
 * @ Check COI to see if annual disclosure is coming due
 *//*from  w w w.j a  v  a 2s  .c  om*/
public List<String> getMessages() {
    List<String> results = new ArrayList<String>();

    UserSession session = GlobalVariables.getUserSession();
    if (session != null && StringUtils.isNotEmpty(GlobalVariables.getUserSession().getPrincipalId())) {
        String personId = GlobalVariables.getUserSession().getPrincipalId();
        String renewalDateString = getParameterService().getParameterValueAsString(
                Constants.MODULE_NAMESPACE_COIDISCLOSURE, ParameterConstants.DOCUMENT_COMPONENT,
                "ANNUAL_DISCLOSURE_RENEWAL_DATE");
        LOG.debug("renewalDateString=" + renewalDateString);
        if (StringUtils.isNotEmpty(renewalDateString)) {
            Date renewalDue = null;
            try {
                renewalDue = new Date(new SimpleDateFormat("MM/dd/yyyy").parse(renewalDateString).getTime());
            } catch (Exception e) {
                LOG.error(
                        "***** no valid Annual Disclosure Certification renewal date found.  Defaulting to anniversary of last Annual");
            }
            String advanceNoticeString = getParameterService().getParameterValueAsString(
                    Constants.MODULE_NAMESPACE_COIDISCLOSURE, ParameterConstants.DOCUMENT_COMPONENT,
                    "ANNUAL_DISCLOSURE_ADVANCE_NOTICE");
            int advanceDays = -1;
            try {
                advanceDays = Integer.parseInt(advanceNoticeString);
            } catch (Exception e) {
                LOG.error(
                        "***** no valid Annual Disclosure Certification advance notice parameter found.  Defaulting to 30 days.");
                advanceDays = 30;
            }
            LOG.debug("advanceDays=" + advanceDays);
            // find latest existing annual review
            Map<String, Object> fieldValues = new HashMap<String, Object>();
            fieldValues.put("personId", personId);
            fieldValues.put("eventTypeCode", CoiDisclosureEventType.ANNUAL);
            List<CoiDisclosure> annualDisclosures = (List<CoiDisclosure>) businessObjectService
                    .findMatching(CoiDisclosure.class, fieldValues);
            Timestamp lastAnnualDate = null;
            for (CoiDisclosure disclosure : annualDisclosures) {
                final Timestamp disclosureCertificationTimestamp = disclosure.getCertificationTimestamp();
                if (disclosureCertificationTimestamp != null) {
                    if (lastAnnualDate == null || lastAnnualDate.before(disclosureCertificationTimestamp)) {
                        lastAnnualDate = disclosureCertificationTimestamp;
                    }
                }
            }
            Calendar lastAnnualCalendar = null;
            if (lastAnnualDate != null) {
                lastAnnualCalendar = Calendar.getInstance();
                lastAnnualCalendar.setTimeInMillis(lastAnnualDate.getTime());
            }
            final Calendar currentTime = Calendar.getInstance();
            boolean sendErrorWithDate = false;
            boolean sendError = false;
            LOG.debug("renewalDue=" + renewalDue);
            if (renewalDue != null) {
                final Calendar reminderDate = Calendar.getInstance();
                reminderDate.setTimeInMillis(renewalDue.getTime());
                reminderDate.add(Calendar.DATE, -advanceDays);
                if (currentTime.after(reminderDate)
                        && ((lastAnnualCalendar == null) || currentTime.after(lastAnnualCalendar))) {
                    sendErrorWithDate = true;
                }
            } else {
                final Calendar dueCalendarDate = Calendar.getInstance();
                if (lastAnnualDate == null) {
                    sendError = true;
                } else {
                    dueCalendarDate.setTimeInMillis(lastAnnualDate.getTime());
                    dueCalendarDate.add(Calendar.YEAR, 1);
                    dueCalendarDate.add(Calendar.DATE, -1);
                    renewalDue = new Date(dueCalendarDate.getTimeInMillis());
                    final Calendar reminderDate = Calendar.getInstance();
                    reminderDate.setTimeInMillis(renewalDue.getTime());
                    reminderDate.add(Calendar.DATE, -advanceDays);
                    if (currentTime.after(reminderDate)) {
                        sendErrorWithDate = true;
                    }
                }
            }
            if (sendError) {
                String msg = getConfigurationService()
                        .getPropertyValueAsString("annual.disclosure.due.message");
                if (!StringUtils.isEmpty(msg)) {
                    results.add(msg);
                }
            }
            if (sendErrorWithDate) {
                String msg = getConfigurationService()
                        .getPropertyValueAsString("annual.disclosure.due.message.with.date");
                if (!StringUtils.isEmpty(msg)) {
                    results.add(msg.replace("{0}", new SimpleDateFormat("MM/dd/yyyy").format(renewalDue)));
                }
            }
        }
    }
    return results;
}

From source file:nl.strohalm.cyclos.services.elements.ReferenceServiceImpl.java

@Override
public boolean canReplyFeedbackNow(final TransactionFeedback transactionFeedback) {
    Payment payment = transactionFeedback.getPayment();
    Calendar date = transactionFeedback.getDate();
    final Calendar replyLimit = payment.getType().getFeedbackReplyExpirationTime().add(date);
    return replyLimit.after(Calendar.getInstance());
}

From source file:org.eredlab.g4.ccl.net.ftp.parser.FTPTimestampParserImpl.java

/** 
 * Implements the one {@link  FTPTimestampParser#parseTimestamp(String)  method}
 * in the {@link  FTPTimestampParser  FTPTimestampParser} interface 
 * according to this algorithm:/*from  ww  w . ja v a 2s .co  m*/
 * 
 * If the recentDateFormat member has been defined, try to parse the 
 * supplied string with that.  If that parse fails, or if the recentDateFormat
 * member has not been defined, attempt to parse with the defaultDateFormat
 * member.  If that fails, throw a ParseException. 
 * 
 * @see org.apache.commons.net.ftp.parser.FTPTimestampParser#parseTimestamp(java.lang.String)    
 */
/* (non-Javadoc)
 * 
 */
public Calendar parseTimestamp(String timestampStr) throws ParseException {
    Calendar now = Calendar.getInstance();
    now.setTimeZone(this.getServerTimeZone());

    Calendar working = Calendar.getInstance();
    working.setTimeZone(this.getServerTimeZone());
    ParsePosition pp = new ParsePosition(0);

    Date parsed = null;
    if (this.recentDateFormat != null) {
        parsed = recentDateFormat.parse(timestampStr, pp);
    }
    if (parsed != null && pp.getIndex() == timestampStr.length()) {
        working.setTime(parsed);
        working.set(Calendar.YEAR, now.get(Calendar.YEAR));
        if (working.after(now)) {
            working.add(Calendar.YEAR, -1);
        }
    } else {
        pp = new ParsePosition(0);
        parsed = defaultDateFormat.parse(timestampStr, pp);
        // note, length checks are mandatory for us since
        // SimpleDateFormat methods will succeed if less than
        // full string is matched.  They will also accept, 
        // despite "leniency" setting, a two-digit number as
        // a valid year (e.g. 22:04 will parse as 22 A.D.) 
        // so could mistakenly confuse an hour with a year, 
        // if we don't insist on full length parsing.
        if (parsed != null && pp.getIndex() == timestampStr.length()) {
            working.setTime(parsed);
        } else {
            throw new ParseException("Timestamp could not be parsed with older or recent DateFormat",
                    pp.getIndex());
        }
    }
    return working;
}