Example usage for org.joda.time DateTime plusMonths

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

Introduction

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

Prototype

public DateTime plusMonths(int months) 

Source Link

Document

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

Usage

From source file:org.apache.beam.sdk.extensions.sql.impl.interpreter.operator.date.BeamSqlDatetimePlusExpression.java

License:Apache License

private DateTime addInterval(DateTime dateTime, SqlTypeName intervalType, int numberOfIntervals) {
    switch (intervalType) {
    case INTERVAL_SECOND:
        return dateTime.plusSeconds(numberOfIntervals);
    case INTERVAL_MINUTE:
        return dateTime.plusMinutes(numberOfIntervals);
    case INTERVAL_HOUR:
        return dateTime.plusHours(numberOfIntervals);
    case INTERVAL_DAY:
        return dateTime.plusDays(numberOfIntervals);
    case INTERVAL_MONTH:
        return dateTime.plusMonths(numberOfIntervals);
    case INTERVAL_YEAR:
        return dateTime.plusYears(numberOfIntervals);
    default://from  ww w  . ja va  2 s  . c om
        throw new IllegalArgumentException("Adding " + intervalType.getName() + " to date is not supported");
    }
}

From source file:org.apache.falcon.execution.SchedulerUtil.java

License:Apache License

/**
 * Returns the frequency in millis from the given time.
 * Needs to take the calender into account.
 * @param referenceTime/*w  w  w .ja  v a 2  s.  c  o  m*/
 * @param frequency
 * @return
 */
public static long getFrequencyInMillis(DateTime referenceTime, Frequency frequency) {
    switch (frequency.getTimeUnit()) {
    case minutes:
        return MINUTE_IN_MS * frequency.getFrequencyAsInt();
    case hours:
        return HOUR_IN_MS * frequency.getFrequencyAsInt();
    case days:
        return referenceTime.plusDays(frequency.getFrequencyAsInt()).getMillis() - referenceTime.getMillis();
    case months:
        return referenceTime.plusMonths(frequency.getFrequencyAsInt()).getMillis() - referenceTime.getMillis();
    default:
        throw new IllegalArgumentException("Invalid time unit " + frequency.getTimeUnit().name());
    }
}

From source file:org.apache.flume.ext.source.SyslogParser.java

License:Apache License

/**
 * Parse the RFC3164 date format. This is trickier than it sounds because this
 * format does not specify a year so we get weird edge cases at year
 * boundaries. This implementation tries to "do what I mean".
 * @param ts RFC3164-compatible timestamp to be parsed
 * @return Typical (for Java) milliseconds since the UNIX epoch
 *///w w w .j ava2 s  .  c o  m
protected long parseRfc3164Time(String ts) {
    DateTime now = DateTime.now();
    int year = now.getYear();

    ts = TWO_SPACES.matcher(ts).replaceFirst(" ");

    DateTime date;
    try {
        date = rfc3164Format.parseDateTime(ts);
    } catch (IllegalArgumentException e) {
        logger.debug("rfc3164 date parse failed on (" + ts + "): invalid format", e);
        return 0;
    }

    // try to deal with boundary cases, i.e. new year's eve.
    // rfc3164 dates are really dumb.
    // NB: cannot handle replaying of old logs or going back to the future
    if (date != null) {
        DateTime fixed = date.withYear(year);

        // flume clock is ahead or there is some latency, and the year rolled
        if (fixed.isAfter(now) && fixed.minusMonths(1).isAfter(now)) {
            fixed = date.withYear(year - 1);
            // flume clock is behind and the year rolled
        } else if (fixed.isBefore(now) && fixed.plusMonths(1).isBefore(now)) {
            fixed = date.withYear(year + 1);
        }
        date = fixed;
    }

    if (date == null) {
        return 0;
    }

    return date.getMillis();
}

From source file:org.apache.flume.serialization.SyslogAvroEventSerializer.java

License:Apache License

/**
 * Returns epoch time in millis, or 0 if the string cannot be parsed.
 * We use two date formats because the date spec in rfc3164 is kind of weird.
 * <br/>/* w  w w  .j  a  va2 s  .  c o m*/
 * <b>Warning:</b> logic is used here to determine the year even though it's
 * not part of the timestamp format, and we assume that the machine running
 * Flume has a clock that is at least close to the same day as the machine
 * that generated the event. We also assume that the event was generated
 * recently.
 */
private static long parseRfc3164Date(String in) {
    DateTime date = null;
    try {
        date = dateFmt1.parseDateTime(in);
    } catch (IllegalArgumentException e) {
        // ignore the exception, we act based on nullity of date object
        logger.debug("Date parse failed on ({}), trying single-digit date", in);
    }

    if (date == null) {
        try {
            date = dateFmt2.parseDateTime(in);
        } catch (IllegalArgumentException e) {
            // ignore the exception, we act based on nullity of date object
            logger.debug("2nd date parse failed on ({}), unknown date format", in);
        }
    }

    // hacky stuff to try and deal with boundary cases, i.e. new year's eve.
    // rfc3164 dates are really dumb.
    // NB: cannot handle replaying of old logs or going back to the future
    if (date != null) {
        DateTime now = new DateTime();
        int year = now.getYear();
        DateTime corrected = date.withYear(year);

        // flume clock is ahead or there is some latency, and the year rolled
        if (corrected.isAfter(now) && corrected.minusMonths(1).isAfter(now)) {
            corrected = date.withYear(year - 1);
            // flume clock is behind and the year rolled
        } else if (corrected.isBefore(now) && corrected.plusMonths(1).isBefore(now)) {
            corrected = date.withYear(year + 1);
        }
        date = corrected;
    }

    if (date == null) {
        return 0;
    }

    return date.getMillis();
}

From source file:org.beer30.jdefault.JDefaultBusiness.java

License:Apache License

/**
 * Typically Cards are good for 3 years. Will create a random date between 24 and 48 months
 *
 * @return date/*from   ww  w.ja  v a2 s . c o m*/
 */
public static Date creditCardExpiryDate() {
    DateTime dateTime = new DateTime();
    DateTime addedMonths = dateTime.plusMonths(JDefaultNumber.randomIntBetweenTwoNumbers(24, 48));
    return addedMonths.dayOfMonth().withMaximumValue().toDate();
}

From source file:org.callistasoftware.netcare.model.entity.HealthPlanEntity.java

License:Open Source License

protected void calculateEnd() {
    if (durationUnit != null && startDate != null) {

        final DateTime dt = new DateTime(getStartDate());
        if (getDurationUnit().equals(DurationUnit.MONTH)) {
            setEndDate(dt.plusMonths(getDuration()).withTime(23, 59, 59, 999).toDate());
        } else {//from  w  ww .  j  a  v  a 2s  .c om
            setEndDate(dt.plusWeeks(getDuration()).withTime(23, 59, 59, 999).toDate());
        }
    } else {
        endDate = null;
    }
}

From source file:org.catrobat.jira.timesheet.services.impl.TimesheetEntryServiceImpl.java

License:Apache License

@Override
public int getHoursOfLastXMonths(Timesheet sheet, int months) {
    DateTime now = DateTime.now();//w  ww  . j av a 2 s.  co  m
    int minutes = 0;
    for (TimesheetEntry entry : getEntriesBySheet(sheet)) {
        DateTime beginDate = new DateTime(entry.getBeginDate());
        if (beginDate.plusMonths(months).compareTo(now) >= 0) {
            minutes += entry.getDurationMinutes();
        }
    }
    return minutes / 60;
}

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

License:Apache License

/**
 * Gets the criteria.// w ww .  ja v a  2 s.  co m
 *
 * @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/*from ww  w.java 2 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:/* 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;
}