Example usage for org.joda.time DateTime plusYears

List of usage examples for org.joda.time DateTime plusYears

Introduction

In this page you can find the example usage for org.joda.time DateTime plusYears.

Prototype

public DateTime plusYears(int years) 

Source Link

Document

Returns a copy of this datetime plus the specified number of years.

Usage

From source file:org.apache.isis.core.metamodel.facets.value.datetimejoda.JodaDateTimeValueSemanticsProvider.java

License:Apache License

@Override
protected DateTime add(final DateTime original, final int years, final int months, final int days,
        final int hours, final int minutes) {
    if (hours != 0 || minutes != 0) {
        throw new IllegalArgumentException("cannot add non-zero hours or minutes to a DateTime");
    }/*ww  w  .  j av a2  s  .c  o m*/
    return original.plusYears(years).plusMonths(months).plusDays(days);
}

From source file:org.apigw.authserver.svc.impl.TokenServicesImpl.java

License:Open Source License

/**
 * @param residentIdentificationNumber in format yyyyMMddnnnn- for example 199212319876
 * @param validitySeconds - for example 43200  (60 * 60 * 12) - 12 hours in the future
 * @return/*from   ww  w.  j  a v  a2s. c o m*/
 */
protected Date generateExpirationTime(String residentIdentificationNumber, long validitySeconds) {
    if (residentIdentificationNumber == null || residentIdentificationNumber.length() < 8) {
        throw new IllegalArgumentException(
                "Invalid residentIdentificationNumber " + residentIdentificationNumber);
    }
    long validityMilliseconds = validitySeconds * 1000L;
    final String birthdayString = residentIdentificationNumber.substring(0, 8);
    final DateTime birthDate = DateTime.parse(birthdayString, ISODateTimeFormat.basicDate());
    Period period = new Period(birthDate, new DateTime(), PeriodType.yearMonthDay());
    DateTime birthDatePlusLegalGuardianAgeLimit = birthDate.plusYears(legalGuardianAgeLimit);
    DateTime residentAdultDate = birthDate.plusYears(adultAge);
    DateTime expiration = new DateTime().withTimeAtStartOfDay(); //defaulting to midnight of today (token will be immediately invalid)
    if (validitySeconds > 0) {
        // Standard expiration
        final DateTime standardExpiration = new DateTime().plus(validityMilliseconds);
        if (birthDatePlusLegalGuardianAgeLimit.isAfter(now().plus(validityMilliseconds))) { // resident will hit the legal guardian age after max token validity
            expiration = standardExpiration;
        } else if (residentAdultDate.isBeforeNow()) { // resident is considered adult
            expiration = standardExpiration;
        } else if (birthDatePlusLegalGuardianAgeLimit.isAfterNow()) { //resident will hit the legal guardian age before max token validity
            expiration = birthDatePlusLegalGuardianAgeLimit;
        }
        // if we get here resident has passed legal guardian age but is not considered adult, using default
    }
    log.debug("calculated token exp time for resident who is ~ {} years, {} months and {} days old to {}",
            period.getYears(), period.getMonths(), period.getDays(), expiration);
    return expiration.toDate();
}

From source file:org.broadleafcommerce.core.web.controller.checkout.BroadleafCheckoutController.java

License:Apache License

/**
 * A helper method used to construct a list of Credit Card Expiration Years
 * Useful for expiration dropdown menus.
 *
 * @return List of the next ten years starting with the current year.
 */// ww w.  jav  a2s  . c o  m
protected List<String> populateExpirationYears() {
    List<String> expirationYears = new ArrayList<String>();
    DateTime dateTime = new DateTime();
    for (int i = 0; i < 10; i++) {
        expirationYears.add(dateTime.plusYears(i).getYear() + "");
    }
    return expirationYears;
}

From source file:org.efaps.esjp.admin.index.LucenceQueryBuilder_Base.java

License:Apache License

/**
 * Gets the criteria.//  ww w .  ja va2 s . com
 *
 * @param _dimValue the _dim value
 * @return the criteria
 */
private StringBuilder getCriteria(final DimValue _dimValue) {
    final StringBuilder ret = new StringBuilder();
    final Dimension dim = EnumUtils.<Indexer.Dimension>getEnum(Indexer.Dimension.class, _dimValue.getPath()[0]);
    switch (dim) {
    case DIMCREATED:
        final DateTime startDate;
        final DateTime endDate;
        // year is selected
        if (_dimValue.getPath().length == 1) {
            startDate = new DateTime().withYear(Integer.parseInt(_dimValue.getLabel())).withDayOfYear(1);
            endDate = startDate.plusYears(1).minusDays(1);
        } else {
            startDate = new DateTime().withYear(Integer.parseInt(_dimValue.getPath()[1]))
                    .withMonthOfYear(Integer.parseInt(_dimValue.getLabel())).withDayOfMonth(1);
            endDate = startDate.plusMonths(1).minusDays(1);
        }
        ret.append(Indexer.Key.CREATEDSTR).append(":[")
                .append(DateTools.dateToString(startDate.toDate(), DateTools.Resolution.DAY)).append(" TO ")
                .append(DateTools.dateToString(endDate.toDate(), DateTools.Resolution.DAY)).append("]");
        break;
    case DIMTYPE:
        ret.append(DBProperties.getProperty("index.Type")).append(":\"").append(_dimValue.getLabel())
                .append("\"");
        break;
    default:
        break;
    }
    return ret;
}

From source file:org.efaps.esjp.common.datetime.JodaTimeUtils.java

License:Apache License

/**
 * @param _parameter parameter as passed by the eFaps API
 * @return new DateTime//  w w w .  ja  v  a2 s.  c  om
 * @throws EFapsException on error
 */
public static DateTime getDefaultvalue(final Parameter _parameter) throws EFapsException {
    final JodaTimeUtils utils = new JodaTimeUtils();
    DateTime ret = new DateTime().withTimeAtStartOfDay()
            .withChronology(Context.getThreadContext().getChronology());
    for (final DateDefaultValues value : DateDefaultValues.values()) {
        if (utils.containsProperty(_parameter, value.toString())) {
            final String strValue = utils.getProperty(_parameter, value.toString());
            switch (value) {
            case TODAY:
                ret = new DateTime().withChronology(Context.getThreadContext().getChronology());
                break;
            case WEEKS:
                ret = ret.plusWeeks(Integer.valueOf(strValue));
                break;
            case MONTHS:
                ret = ret.plusMonths(Integer.valueOf(strValue));
                break;
            case YEARS:
                ret = ret.plusYears(Integer.valueOf(strValue));
                break;
            case WITHDAYOFMONTH:
                ret = ret.withDayOfMonth(Integer.valueOf(strValue));
                break;
            case WITHDAYOFWEEK:
                ret = ret.withDayOfWeek(Integer.valueOf(strValue));
                break;
            case LASTDAYOFMONTH:
                ret = ret.dayOfMonth().withMaximumValue();
                break;
            case WITHDAYOFYEAR:
                ret = ret.withDayOfYear(Integer.valueOf(strValue));
            default:
                break;
            }
        }
    }
    return ret;
}

From source file:org.efaps.esjp.common.uiform.Field_Base.java

License:Apache License

/**
 * Method to get a Datevalue for a field on create to set a more "intelligent"
 * value like "monday of current week" etc.
 * Properties://from ww  w. j  a v a  2  s .  c  o  m
 * <table>
 *  <tr><th>Property</th><th>Value</th><th>Description</th></tr>
 *  <tr><td>withDayOfWeek</td><td>1,2,3,4,5,6,7</td>
 *      <td>the Integer represents on of the weekdays starting with Monday, Tuesday...</td></tr>
 *  <tr><td>withDayOfMonth</td><td>Integer</td><td>day of month</td></tr>
 *  <tr><td>minusDays</td><td>Integer</td><td>days to subtract</td></tr>
 *  <tr><td>plusDays</td><td>Integer</td><td>days to add</td></tr>
 *  <tr><td>minusWeeks</td><td>Integer</td><td>weeks to subtract</td></tr>
 *  <tr><td>plusWeeks</td><td>Integer</td><td>weeks to add</td></tr>
 * </table>
 *
 * @param _parameter Parameter as passed by the eFaps API
 * @return ReturnValue containing the date
 * @throws EFapsException on error
 */
public Return getDefault4DateFieldValue(final Parameter _parameter) throws EFapsException {
    final Return ret = new Return();
    final TargetMode mode = (TargetMode) _parameter.get(ParameterValues.ACCESSMODE);
    final Collection<TargetMode> modes = new ArrayList<>();
    for (final String aMode : analyseProperty(_parameter, "TargetMode").values()) {
        modes.add(EnumUtils.getEnum(TargetMode.class, aMode.toUpperCase()));
    }
    if ((TargetMode.CREATE.equals(mode) || TargetMode.EDIT.equals(mode))
            && (modes.isEmpty() || modes.contains(mode))) {
        DateTime date = new DateTime();
        if (containsProperty(_parameter, "withDayOfWeek")) {
            final int dayOfWeek = Integer.parseInt(getProperty(_parameter, "withDayOfWeek"));
            date = date.withDayOfWeek(dayOfWeek);
        }
        if (containsProperty(_parameter, "withDayOfMonth")) {
            final int dayOfMonth = Integer.parseInt(getProperty(_parameter, "withDayOfMonth"));
            date = date.withDayOfMonth(dayOfMonth);
        }
        if (containsProperty(_parameter, "days")) {
            final int days = Integer.parseInt(getProperty(_parameter, "days"));
            date = date.plusDays(days);
        }
        if (containsProperty(_parameter, "weeks")) {
            final int weeks = Integer.parseInt(getProperty(_parameter, "weeks"));
            date = date.plusWeeks(weeks);
        }
        if (containsProperty(_parameter, "months")) {
            final int months = Integer.parseInt(getProperty(_parameter, "months"));
            date = date.plusMonths(months);
        }
        if (containsProperty(_parameter, "years")) {
            final int years = Integer.parseInt(getProperty(_parameter, "years"));
            date = date.plusYears(years);
        }
        ret.put(ReturnValues.VALUES, date);
    }
    return ret;
}

From source file:org.efaps.esjp.common.uitable.MultiPrint_Base.java

License:Apache License

/**
 * @param _field Field the date is wanted for
 * @return datetime array//from w w  w .j  a v  a 2 s  .  c o m
 * @throws EFapsException on error
 */
protected Object[] getFilter(final Field _field) throws EFapsException {
    Object[] ret = null;
    final String filter = _field.getFilter().getDefaultValue();
    if (filter != null) {
        final String[] parts = filter.split(":");
        final String range = parts[0];
        final int fromSub = parts.length > 1 ? Integer.parseInt(parts[1]) : 0;
        final int rangeCount = parts.length > 2 ? Integer.parseInt(parts[2]) : 1;
        DateTime dateFrom = new DateTime();
        DateTime dateTo = new DateTime();
        if (range != null) {
            final FilterDefault def = FilterDefault.valueOf(range.toUpperCase());
            // to get a timezone dependent DateTim
            DateTime tmp = DateTimeUtil.translateFromUI(new DateTime()).withTimeAtStartOfDay();
            switch (def) {
            case TODAY:
                dateFrom = tmp.toDateTime().minusDays(fromSub).minusMinutes(1);
                dateTo = dateFrom.plusDays(rangeCount).plusSeconds(1);
                ret = new DateTime[] { dateFrom, dateTo };
                break;
            case WEEK:
                // the first of the current week
                tmp = tmp.minusDays(tmp.getDayOfWeek() - 1);
                dateFrom = tmp.minusWeeks(fromSub).minusMinutes(1);
                dateTo = tmp.plusWeeks(rangeCount);
                ret = new DateTime[] { dateFrom, dateTo };
                break;
            case MONTH:
                // the first of the current month
                tmp = tmp.minusDays(tmp.getDayOfMonth() - 1);
                // substract the month and a minute before
                dateFrom = tmp.minusMonths(fromSub).minusMinutes(1);
                // add the month
                dateTo = tmp.plusMonths(rangeCount);
                ret = new DateTime[] { dateFrom, dateTo };
                break;
            case YEAR:
                tmp = tmp.minusDays(tmp.getDayOfYear() - 1);
                dateFrom = tmp.minusYears(fromSub).minusMinutes(1);
                dateTo = tmp.plusYears(rangeCount);
                ret = new DateTime[] { dateFrom, dateTo };
                break;
            case ALL:
                ret = new String[] { "*" };
                break;
            case NONE:
                break;
            default:
                ret = new String[] { range + "*" };
                break;
            }
        }
    }
    return ret;
}

From source file:org.emonocot.model.registry.Resource.java

License:Open Source License

public void updateNextAvailableDate() {
    if (getScheduled()) {
        DateTime nextAvailableDate = new DateTime();
        switch (getSchedulingPeriod()) {
        case YEARLY:
            nextAvailableDate = nextAvailableDate.plusYears(1);
            break;
        case MONTHLY:
            nextAvailableDate = nextAvailableDate.plusMonths(1);
            break;
        case WEEKLY:
            nextAvailableDate = nextAvailableDate.plusWeeks(1);
            break;
        case DAILY:
            nextAvailableDate = nextAvailableDate.plusDays(1);
            break;
        default://from  w ww.j a  v a  2  s .  com
            nextAvailableDate = null;
        }

        setNextAvailableDate(nextAvailableDate);
    }
}

From source file:org.emonocot.portal.view.Functions.java

License:Open Source License

public static String formatDateRange(String dateRange) {

    Matcher matcher = pattern.matcher(dateRange);

    if (matcher.matches()) {
        String beginningString = matcher.group(1);
        String endString = matcher.group(2);

        DateTime beginning = solrDateTimeFormatter.parseDateTime(beginningString);
        DateTime end = solrDateTimeFormatter.parseDateTime(endString);
        Integer gap = Integer.parseInt(matcher.group(3));
        String increment = matcher.group(4);
        DateTimeFormatter dateTimeFormatter = null;
        switch (increment) {
        case "DAY":
            end = end.plusDays(gap);// w w  w.j a v a 2s  .c om
            dateTimeFormatter = DateTimeFormat.shortDate();
            break;
        case "WEEK":
            end = end.plusWeeks(gap);
            dateTimeFormatter = DateTimeFormat.shortDate();
            break;
        case "MONTH":
            end = end.plusMonths(gap);
            dateTimeFormatter = DateTimeFormat.forPattern("yyyy/MM");
            break;
        case "YEAR":
            end = end.plusYears(gap);
            dateTimeFormatter = DateTimeFormat.forPattern("yyyy");
            break;
        }

        return dateTimeFormatter.print(beginning) + " - " + dateTimeFormatter.print(end);

    } else {
        return dateRange;
    }

}

From source file:org.epics.archiverappliance.common.TimeUtils.java

/**
 * Given an epoch seconds and a granularity, this method gives you the first second in the next partition as epoch seconds.
 * @param epochSeconds//from   w ww .j a  v  a 2  s.  c  o  m
 * @param granularity
 * @return
 */
public static long getNextPartitionFirstSecond(long epochSeconds, PartitionGranularity granularity) {
    DateTime dateTime = new DateTime(epochSeconds * 1000, DateTimeZone.UTC);
    DateTime nextPartitionFirstSecond = null;
    switch (granularity) {
    case PARTITION_YEAR:
        nextPartitionFirstSecond = dateTime.plusYears(1).withMonthOfYear(1).withDayOfMonth(1).withHourOfDay(0)
                .withMinuteOfHour(0).withSecondOfMinute(0);
        return nextPartitionFirstSecond.getMillis() / 1000;
    case PARTITION_MONTH:
        nextPartitionFirstSecond = dateTime.plusMonths(1).withDayOfMonth(1).withHourOfDay(0).withMinuteOfHour(0)
                .withSecondOfMinute(0);
        return nextPartitionFirstSecond.getMillis() / 1000;
    case PARTITION_DAY:
        nextPartitionFirstSecond = dateTime.plusDays(1).withHourOfDay(0).withMinuteOfHour(0)
                .withSecondOfMinute(0);
        return nextPartitionFirstSecond.getMillis() / 1000;
    case PARTITION_HOUR:
        nextPartitionFirstSecond = dateTime.plusHours(1).withMinuteOfHour(0).withSecondOfMinute(0);
        return nextPartitionFirstSecond.getMillis() / 1000;
    case PARTITION_5MIN:
    case PARTITION_15MIN:
    case PARTITION_30MIN:
        int approxMinutesPerChunk = granularity.getApproxMinutesPerChunk();
        DateTime nextPartForMin = dateTime.plusMinutes(approxMinutesPerChunk);
        int startOfPartitionForMin = (nextPartForMin.getMinuteOfHour() / approxMinutesPerChunk)
                * approxMinutesPerChunk;
        nextPartitionFirstSecond = nextPartForMin.withMinuteOfHour(startOfPartitionForMin)
                .withSecondOfMinute(0);
        return nextPartitionFirstSecond.getMillis() / 1000;
    default:
        throw new UnsupportedOperationException("Invalid Partition type " + granularity);
    }
}