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:com.marklogic.samplestack.dbclient.DateFacetBuilder.java

License:Apache License

public static ObjectNode dateFacet(DateTime min, DateTime max) {
    DateFacetBuilder fb = new DateFacetBuilder(new CustomObjectMapper());
    fb.name("date");
    /*/*ww  w. java2s  .c o  m*/
    long interval = max.getMillis() - min.getMillis();
    if (interval / BucketInterval.BY_DAY.bucketDuration() < 40) {
       fb.period("DAY");
       DateTime bucketStart = min.minus(min.getMillisOfDay());
       while (bucketStart.isBefore(max)) {
    DateTime bucketEnd = bucketStart.plusDays(1);
    fb.bucket(bucketStart, bucketEnd);
    bucketStart = bucketStart.plusDays(1);
       }
    }
    else if (interval / BucketInterval.BY_WEEK.bucketDuration() < 40) {
       fb.period("WEEK");
       DateTime bucketStart = min.minusDays(min.getDayOfWeek()).minus(min.getMillisOfDay());
       while (bucketStart.isBefore(max)) {
    DateTime bucketEnd = bucketStart.plusWeeks(1);
    fb.bucket(bucketStart, bucketEnd);
    bucketStart = bucketStart.plusWeeks(1);
       }
    } else {
    */
    // for 8.0-1 we are only doing facets by month
    fb.period("MONTH");
    DateTime bucketStart = min.minusDays(min.getDayOfMonth() - 1).minus(min.getMillisOfDay());
    bucketStart = new DateTime(bucketStart);
    while (bucketStart.isBefore(max)) {
        DateTime bucketEnd = bucketStart.plusMonths(1);
        fb.bucket(bucketStart, bucketEnd);
        bucketStart = bucketStart.plusMonths(1);
    }
    // }
    return fb.facetNode;
}

From source file:com.money.manager.ex.servicelayer.RecurringTransactionService.java

License:Open Source License

/**
 * @param date    to start calculate/*from   w  w  w  . ja v a  2s. co m*/
 * @param repeatType type of repeating transactions
 * @param numberOfPeriods Number of instances (days, months) parameter. Used for In (x) Days, for
 *                  example to indicate x.
 * @return next Date
 */
public DateTime getNextScheduledDate(DateTime date, Recurrence repeatType, Integer numberOfPeriods) {
    if (numberOfPeriods == null || numberOfPeriods == Constants.NOT_SET) {
        numberOfPeriods = 0;
    }

    if (repeatType.getValue() >= 200) {
        repeatType = Recurrence.valueOf(repeatType.getValue() - 200);
    } // set auto execute without user acknowledgement
    if (repeatType.getValue() >= 100) {
        repeatType = Recurrence.valueOf(repeatType.getValue() - 100);
    } // set auto execute on the next occurrence

    DateTime result = new DateTime(date);

    switch (repeatType) {
    case ONCE: //none
        break;
    case WEEKLY: //weekly
        result = result.plusWeeks(1);
        break;
    case BIWEEKLY: //bi_weekly
        result = result.plusWeeks(2);
        break;
    case MONTHLY: //monthly
        result = result.plusMonths(1);
        break;
    case BIMONTHLY: //bi_monthly
        result = result.plusMonths(2);
        break;
    case QUARTERLY: //quarterly
        result = result.plusMonths(3);
        break;
    case SEMIANNUALLY: //half_year
        result = result.plusMonths(6);
        break;
    case ANNUALLY: //yearly
        result = result.plusYears(1);
        break;
    case FOUR_MONTHS: //four_months
        result = result.plusMonths(4);
        break;
    case FOUR_WEEKS: //four_weeks
        result = result.plusWeeks(4);
        break;
    case DAILY: //daily
        result = result.plusDays(1);
        break;
    case IN_X_DAYS: //in_x_days
    case EVERY_X_DAYS: //every_x_days
        result = result.plusDays(numberOfPeriods);
        break;
    case IN_X_MONTHS: //in_x_months
    case EVERY_X_MONTHS: //every_x_months
        result = result.plusMonths(numberOfPeriods);
        break;
    case MONTHLY_LAST_DAY: //month (last day)
        // if the date is not the last day of this month, set it to the end of the month.
        // else set it to the end of the next month.
        DateTime lastDayOfMonth = MmxDateTimeUtils.getLastDayOfMonth(result);
        if (!result.equals(lastDayOfMonth)) {
            // set to last day of the month
            result = lastDayOfMonth;
        } else {
            result = lastDayOfMonth.plusMonths(1);
        }
        break;

    case MONTHLY_LAST_BUSINESS_DAY: //month (last business day)
        // if the date is not the last day of this month, set it to the end of the month.
        // else set it to the end of the next month.
        DateTime lastDayOfMonth2 = MmxDateTimeUtils.getLastDayOfMonth(result);
        if (!result.equals(lastDayOfMonth2)) {
            // set to last day of the month
            result = lastDayOfMonth2;
        } else {
            result = lastDayOfMonth2.plusMonths(1);
        }
        // get the last day of the next month,
        // then iterate backwards until we are on a weekday.
        while (result.getDayOfWeek() == DateTimeConstants.SATURDAY
                || result.getDayOfWeek() == DateTimeConstants.SUNDAY) {
            result = result.minusDays(1);
        }
        break;
    }
    return result;
}

From source file:com.mycompany.alarmdatasimulator.Main.java

public static void main(String[] args) {
    Map<Alarm, Map<Alarm, CausalRelation>> relations = getCenarioTeste2(); // Relations map
    SimulationExecutor exec = new SimulationExecutor(relations);

    DateTime init = new DateTime(2010, 5, 1, 1, 0, 0); // Initial time simulation
    Duration duration = new Duration(init, init.plusMonths(5)); // Duration of simulation, in months
    String result = exec.simulate(init, duration);
    System.out.println(result); // Print result as CSV pattern

}

From source file:com.netflix.ice.basic.BasicDataManager.java

License:Apache License

private double[] getData(Interval interval, TagLists tagLists) throws ExecutionException {
    DateTime start = config.startDate;
    DateTime end = config.startDate;//from   ww  w.  j  av a 2 s . co  m

    if (consolidateType == ConsolidateType.hourly) {
        start = interval.getStart().withDayOfMonth(1).withMillisOfDay(0);
        end = interval.getEnd();
    } else if (consolidateType == ConsolidateType.daily) {
        start = interval.getStart().withDayOfYear(1).withMillisOfDay(0);
        end = interval.getEnd();
    }

    int num = 0;
    if (consolidateType == ConsolidateType.hourly) {
        num = interval.toPeriod(PeriodType.hours()).getHours();
        if (interval.getStart().plusHours(num).isBefore(interval.getEnd()))
            num++;
    } else if (consolidateType == ConsolidateType.daily) {
        num = interval.toPeriod(PeriodType.days()).getDays();
        if (interval.getStart().plusDays(num).isBefore(interval.getEnd()))
            num++;
    } else if (consolidateType == ConsolidateType.weekly) {
        num = interval.toPeriod(PeriodType.weeks()).getWeeks();
        if (interval.getStart().plusWeeks(num).isBefore(interval.getEnd()))
            num++;
    } else if (consolidateType == ConsolidateType.monthly) {
        num = interval.toPeriod(PeriodType.months()).getMonths();
        if (interval.getStart().plusMonths(num).isBefore(interval.getEnd()))
            num++;
    }

    double[] result = new double[num];

    do {
        ReadOnlyData data = getReadOnlyData(start);

        int resultIndex = 0;
        int fromIndex = 0;

        if (interval.getStart().isBefore(start)) {
            if (consolidateType == ConsolidateType.hourly) {
                resultIndex = Hours.hoursBetween(interval.getStart(), start).getHours();
            } else if (consolidateType == ConsolidateType.daily) {
                resultIndex = Days.daysBetween(interval.getStart(), start).getDays();
            } else if (consolidateType == ConsolidateType.weekly) {
                resultIndex = Weeks.weeksBetween(interval.getStart(), start).getWeeks();
            } else if (consolidateType == ConsolidateType.monthly) {
                resultIndex = Months.monthsBetween(interval.getStart(), start).getMonths();
            }
        } else {
            if (consolidateType == ConsolidateType.hourly) {
                fromIndex = Hours.hoursBetween(start, interval.getStart()).getHours();
            } else if (consolidateType == ConsolidateType.daily) {
                fromIndex = Days.daysBetween(start, interval.getStart()).getDays();
            } else if (consolidateType == ConsolidateType.weekly) {
                fromIndex = Weeks.weeksBetween(start, interval.getStart()).getWeeks();
                if (start.getDayOfWeek() != interval.getStart().getDayOfWeek())
                    fromIndex++;
            } else if (consolidateType == ConsolidateType.monthly) {
                fromIndex = Months.monthsBetween(start, interval.getStart()).getMonths();
            }
        }

        List<Integer> columeIndexs = Lists.newArrayList();
        int columeIndex = 0;
        for (TagGroup tagGroup : data.getTagGroups()) {
            if (tagLists.contains(tagGroup))
                columeIndexs.add(columeIndex);
            columeIndex++;
        }
        while (resultIndex < num && fromIndex < data.getNum()) {
            double[] fromData = data.getData(fromIndex++);
            for (Integer cIndex : columeIndexs)
                result[resultIndex] += fromData[cIndex];
            resultIndex++;
        }

        if (consolidateType == ConsolidateType.hourly)
            start = start.plusMonths(1);
        else if (consolidateType == ConsolidateType.daily)
            start = start.plusYears(1);
        else
            break;
    } while (start.isBefore(end));

    return result;
}

From source file:com.netflix.ice.basic.BasicTagGroupManager.java

License:Apache License

private Collection<Long> getMonthMillis(Interval interval) {
    Set<Long> result = Sets.newTreeSet();
    for (Long milli : tagGroups.keySet()) {
        DateTime monthDate = new DateTime(milli, DateTimeZone.UTC);
        if (new Interval(monthDate, monthDate.plusMonths(1)).overlap(interval) != null)
            result.add(milli);//from w ww. j ava 2 s .com
    }

    return result;
}

From source file:com.netflix.ice.basic.BasicThroughputMetricService.java

License:Apache License

public double[] getData(Interval interval, ConsolidateType consolidateType) throws Exception {
    DateTime start = interval.getStart().withDayOfMonth(1).withMillisOfDay(0);
    DateTime end = interval.getEnd();/*from  w  ww .  j  av a  2s . c o  m*/

    int num = interval.toPeriod(PeriodType.hours()).getHours();
    if (interval.getStart().plusHours(num).isBefore(interval.getEnd()))
        num++;

    double[] hourly = new double[num];
    List<Double> monthly = Lists.newArrayList();
    do {
        double total = 0;
        int resultIndex = interval.getStart().isBefore(start)
                ? Hours.hoursBetween(interval.getStart(), start).getHours()
                : 0;
        int fromIndex = interval.getStart().isBefore(start) ? 0
                : Hours.hoursBetween(start, interval.getStart()).getHours();

        double[] data = this.data.get(start);
        while (resultIndex < num && fromIndex < data.length) {
            total += data[fromIndex];
            hourly[resultIndex++] = data[fromIndex++];
        }

        start = start.plusMonths(1);
        monthly.add(total);
    } while (start.isBefore(end));

    int hoursInPeriod = (int) (consolidateType.millis / AwsUtils.hourMillis);
    num = consolidateType == ConsolidateType.monthly ? monthly.size()
            : (int) Math.ceil(1.0 * num / hoursInPeriod);
    double[] result = new double[num];

    if (consolidateType == ConsolidateType.monthly) {
        for (int i = 0; i < num; i++)
            result[i] = monthly.get(i);
    } else {
        for (int i = 0; i < hourly.length; i++)
            result[i / hoursInPeriod] += hourly[i];
    }
    return result;
}

From source file:com.netflix.ice.reader.ReaderConfig.java

License:Apache License

private void readData(Product product, DataManager dataManager, Interval interval,
        ConsolidateType consolidateType) {
    if (consolidateType == ConsolidateType.hourly) {
        DateTime start = interval.getStart().withDayOfMonth(1).withMillisOfDay(0);
        do {//w w w .  j a v a 2s . c  om
            int hours = dataManager.getDataLength(start);
            logger.info("found " + hours + " hours data for " + product + " " + interval);
            start = start.plusMonths(1);
        } while (start.isBefore(interval.getEnd()));
    } else if (consolidateType == ConsolidateType.daily) {
        DateTime start = interval.getStart().withDayOfYear(1).withMillisOfDay(0);
        do {
            dataManager.getDataLength(start);
            start = start.plusYears(1);
        } while (start.isBefore(interval.getEnd()));
    } else {
        dataManager.getData(interval, new TagLists(), TagType.Account, AggregateType.both, false);
    }
}

From source file:com.netflix.raigad.indexmanagement.ElasticSearchIndexManager.java

License:Apache License

/**
 * Courtesy Jae Bae/*  w w  w .  ja va 2s  .c  o m*/
 */
public void preCreateIndex(IndexMetadata indexMetadata, Client esTransportClient)
        throws UnsupportedAutoIndexException {
    logger.info("Running PreCreate Index task");
    IndicesStatusResponse getIndicesResponse = getIndicesStatusResponse(esTransportClient);
    Map<String, IndexStatus> indexStatusMap = getIndicesResponse.getIndices();
    if (!indexStatusMap.isEmpty()) {
        for (String indexNameWithDateSuffix : indexStatusMap.keySet()) {
            if (config.isDebugEnabled())
                logger.debug("Index Name = <" + indexNameWithDateSuffix + ">");
            if (indexMetadata.getIndexNameFilter().filter(indexNameWithDateSuffix)
                    && indexMetadata.getIndexNameFilter().getNamePart(indexNameWithDateSuffix)
                            .equalsIgnoreCase(indexMetadata.getIndexName())) {

                for (int i = 0; i < indexMetadata.getRetentionPeriod(); ++i) {

                    DateTime dt = new DateTime();
                    int addedDate;

                    switch (indexMetadata.getRetentionType()) {
                    case DAILY:
                        dt = dt.plusDays(i);
                        addedDate = Integer.parseInt(String.format("%d%02d%02d", dt.getYear(),
                                dt.getMonthOfYear(), dt.getDayOfMonth()));
                        break;
                    case MONTHLY:
                        dt = dt.plusMonths(i);
                        addedDate = Integer
                                .parseInt(String.format("%d%02d", dt.getYear(), dt.getMonthOfYear()));
                        break;
                    case YEARLY:
                        dt = dt.plusYears(i);
                        addedDate = Integer.parseInt(String.format("%d", dt.getYear()));
                        break;
                    default:
                        throw new UnsupportedAutoIndexException(
                                "Given index is not (DAILY or MONTHLY or YEARLY), please check your configuration.");

                    }

                    if (config.isDebugEnabled())
                        logger.debug("Added Date = " + addedDate);
                    if (!esTransportClient.admin().indices()
                            .prepareExists(indexMetadata.getIndexName() + addedDate).execute()
                            .actionGet(config.getAutoCreateIndexTimeout()).isExists()) {
                        esTransportClient.admin().indices()
                                .prepareCreate(indexMetadata.getIndexName() + addedDate).execute()
                                .actionGet(config.getAutoCreateIndexTimeout());
                        logger.info(indexMetadata.getIndexName() + addedDate + " is created");
                    } else {
                        //TODO: Change to Debug after Testing
                        logger.warn(indexMetadata.getIndexName() + addedDate + " already exists");
                    }
                }
            }
        }
    } else {
        logger.info("No existing indices, hence can not pre-create any indices");
    }
}

From source file:com.netflix.raigad.indexmanagement.IndexUtils.java

License:Apache License

public static int getFutureRetentionDate(IndexMetadata indexMetadata) throws UnsupportedAutoIndexException {

    DateTime dt = new DateTime();
    int currentDate;

    switch (indexMetadata.getRetentionType()) {
    case DAILY:/* w  w  w. j  av  a  2  s .co m*/
        dt = dt.plusDays(indexMetadata.getRetentionPeriod());
        currentDate = Integer
                .parseInt(String.format("%d%02d%02d", dt.getYear(), dt.getMonthOfYear(), dt.getDayOfMonth()));
        break;
    case MONTHLY:
        dt = dt.plusMonths(indexMetadata.getRetentionPeriod());
        currentDate = Integer.parseInt(String.format("%d%02d", dt.getYear(), dt.getMonthOfYear()));
        break;
    case YEARLY:
        dt = dt.plusYears(indexMetadata.getRetentionPeriod());
        currentDate = Integer.parseInt(String.format("%d", dt.getYear()));
        break;
    default:
        throw new UnsupportedAutoIndexException(
                "Given index is not (DAILY or MONTHLY or YEARLY), please check your configuration.");

    }
    return currentDate;
}

From source file:com.netsteadfast.greenstep.bsc.action.MeasureDataCalendarQueryAction.java

License:Apache License

private String handlerDate() throws Exception {
    String dateStr = this.getFields().get("date");
    String frequency = this.getFields().get("frequency");
    String dateStatus = this.getFields().get("dateStatus");
    DateTime dateTime = new DateTime(dateStr);
    if ("-1".equals(dateStatus)) { // 
        if (BscMeasureDataFrequency.FREQUENCY_DAY.equals(frequency)
                || BscMeasureDataFrequency.FREQUENCY_WEEK.equals(frequency)) { // 
            dateTime = dateTime.plusMonths(-1);
        } else { // 
            dateTime = dateTime.plusYears(-1);
        }/*from w  w w .ja v  a 2 s.  c  o m*/
    }
    if ("1".equals(dateStatus)) { // 
        if (BscMeasureDataFrequency.FREQUENCY_DAY.equals(frequency)
                || BscMeasureDataFrequency.FREQUENCY_WEEK.equals(frequency)) { // 
            dateTime = dateTime.plusMonths(1);
        } else { // 
            dateTime = dateTime.plusYears(1);
        }
    }
    return dateTime.toString("yyyy-MM-dd");
}