Example usage for org.joda.time DateTime minusMonths

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

Introduction

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

Prototype

public DateTime minusMonths(int months) 

Source Link

Document

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

Usage

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 av a2  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/>/*from ww  w  .j  av a 2 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.apache.streams.util.DateUtil.java

License:Apache License

public static Set<String> getAliasesForDateRange(DateTime startDate, DateTime endDate, String prefix) {
    Set<String> aliases = new HashSet<String>();
    aliases.add(prefix + "_" + getDateAbbreviation(startDate.getYear(), startDate.getMonthOfYear()));
    if (endDate == null) {
        return aliases;
    }//from   ww w.  jav a2  s  .  c  om
    while (endDate.isAfter(startDate)) {
        aliases.add(prefix + "_" + getDateAbbreviation(endDate.getYear(), endDate.getMonthOfYear()));
        endDate = endDate.minusMonths(1);
    }
    return aliases;
}

From source file:org.cast.cwm.admin.EventLog.java

License:Open Source License

protected void addDateFilter(Form<Object> form) {
    DateTime currentDateTime = new DateTime(new Date());
    toDateM = new Model<Date>(currentDateTime.toDate());
    fromDateM = new Model<Date>(currentDateTime.minusMonths(1).toDate());

    form.add(new DateTextField("from", fromDateM));
    form.add(new DateTextField("to", toDateM));
}

From source file:org.countandra.utils.CountandraUtils.java

License:Apache License

private long getStartMillis(String timeQuery) {
    DateTime dt = new DateTime(DateTimeZone.UTC);

    TimePeriod tq = hshSupportedTimePeriods.get(timeQuery);

    if (tq != null) {
        switch (tq) {
        case THISHOUR:
            return dt.minusHours(1).getMillis();
        case LASTHOUR:
            return dt.minusHours(2).getMillis();
        case LASTTFHOURS:
            return dt.minusHours(24).getMillis();
        case TODAY:
            return dt.minusHours(24).getMillis();
        case YESTERDAY:
            return dt.minusHours(48).getMillis();
        case THISWEEK:
            return dt.minusWeeks(1).getMillis();
        case LASTWEEK:
            return dt.minusWeeks(2).getMillis();
        case THISMONTH:
            return dt.minusMonths(1).getMillis();
        case LASTMONTH:
            return dt.minusMonths(2).getMillis();
        case THISYEAR:
            return dt.minusYears(1).getMillis();
        case LASTYEAR:
            return dt.minusYears(2).getMillis();

        }//w ww .  j  a v  a 2 s.  c o  m

    } else {

        return 0L;
    }

    return 0;

}

From source file:org.countandra.utils.CountandraUtils.java

License:Apache License

private long getEndMillis(String timeQuery) {
    DateTime dt = new DateTime(DateTimeZone.UTC);

    TimePeriod tq = hshSupportedTimePeriods.get(timeQuery);

    if (tq != null) {
        switch (tq) {
        case THISHOUR:
            return dt.getMillis();
        case LASTHOUR:
            return dt.minusHours(1).getMillis();
        case LASTTFHOURS:
            return dt.getMillis();
        case TODAY:
            return dt.getMillis();
        case YESTERDAY:
            return dt.minusHours(24).getMillis();
        case THISWEEK:
            return dt.getMillis();
        case LASTWEEK:
            return dt.minusWeeks(1).getMillis();
        case THISMONTH:
            return dt.getMillis();
        case LASTMONTH:
            return dt.minusMonths(1).getMillis();
        case THISYEAR:
            return dt.getMillis();
        case LASTYEAR:
            return dt.minusYears(1).getMillis();

        }//www.j ava 2 s  .  c  o  m

    } else {

        return 0L;
    }

    return 0L;

}

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/*ww  w  . j a va2 s.com*/
 * @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.egov.pgr.dashboard.service.DashboardService.java

License:Open Source License

public List<Map<String, Object>> getMonthlyAggregate() {
    DateTime currentDate = new DateTime();
    List<Map<String, Object>> dataHolder = constructMonthPlaceHolder(currentDate.minusMonths(6), currentDate,
            "MMM-yyyy");
    for (Object[] compCnt : dashboardRepository.fetchMonthlyAggregateBetween(
            startOfGivenDate(currentDate.minusMonths(6).withDayOfMonth(1)).toDate(),
            endOfGivenDate(currentDate).toDate()))
        for (Map<String, Object> mapdata : dataHolder)
            if (mapdata.containsValue(StringUtils.capitalize(String.valueOf(compCnt[0]).toLowerCase())))
                mapdata.put("y", Integer.valueOf(String.valueOf(compCnt[1])));
    return dataHolder;
}

From source file:org.egov.pgr.dashboard.service.DashboardService.java

License:Open Source License

public List<Map<String, Object>> getCompTypewiseAggregate() {
    DateTime currentDate = new DateTime();
    List<Map<String, Object>> compTypeWiseData = new LinkedList<>();
    long totalOthersCount = 0;
    int topCount = 1;
    for (Object[] complaint : dashboardRepository.fetchComplaintTypeWiseBetween(
            startOfGivenDate(currentDate.minusMonths(6).withDayOfMonth(1)).toDate(),
            endOfGivenDate(currentDate).toDate())) {
        Map<String, Object> compTypewiseCnt = new HashMap<>();
        Integer complaintCount = Integer.valueOf(String.valueOf(complaint[2]));
        if (topCount < 9) {
            compTypewiseCnt.put("name", String.valueOf(complaint[0]));
            compTypewiseCnt.put("ctId", complaint[1]);
            compTypewiseCnt.put("y", complaintCount);
            compTypeWiseData.add(compTypewiseCnt);
            topCount++;//  ww w .  j  a va 2s  .  c om
        } else
            totalOthersCount += complaintCount;
    }

    if (totalOthersCount > 0) {
        Map<String, Object> othersData = new HashMap<>();
        othersData.put("name", "Others");
        othersData.put("ctId", "");
        othersData.put("y", totalOthersCount);
        compTypeWiseData.add(othersData);
    }
    return compTypeWiseData;
}

From source file:org.egov.pgr.dashboard.service.DashboardService.java

License:Open Source License

public Map<String, Object> topComplaints() {
    DateTime currentDate = new DateTime();

    List<Object> dataHolderNumber = constructListOfMonthPlaceHolder(currentDate.minusMonths(5),
            currentDate.plusMonths(1), "MM");
    List<Object> dataHolderString = constructListOfMonthPlaceHolder(currentDate.minusMonths(5),
            currentDate.plusMonths(1), "MMM");
    List<Object[]> topFiveCompTypeData = dashboardRepository.fetchTopComplaintsBetween(
            startOfGivenDate(currentDate.minusMonths(5).withDayOfMonth(1)).toDate(),
            endOfGivenDate(currentDate).toDate());
    List<Object[]> topFiveCompTypeCurrentMonth = dashboardRepository.fetchTopComplaintsForCurrentMonthBetween(
            startOfGivenDate(currentDate.minusMonths(5).withDayOfMonth(1)).toDate(),
            endOfGivenDate(currentDate).toDate());
    Map<Object, Object> constructResultPlaceholder = new LinkedHashMap<>();
    Map<Object, Object> actualdata = new LinkedHashMap<>();
    for (Object complaintType : topFiveCompTypeCurrentMonth)
        for (Object month : dataHolderNumber)
            constructResultPlaceholder.put(month + "-" + complaintType, BigInteger.ZERO);
    for (Object[] top5CompType : topFiveCompTypeData)
        actualdata.put(top5CompType[0] + "-" + top5CompType[2], top5CompType[1]);
    Map<Object, Object> newdata = new LinkedHashMap<>();
    for (Object placeholderMapKey : constructResultPlaceholder.keySet())
        if (actualdata.get(placeholderMapKey) == null)
            newdata.put(placeholderMapKey, BigInteger.ZERO);
        else// www .  ja  va  2s . com
            newdata.put(placeholderMapKey, actualdata.get(placeholderMapKey));
    Map<String, Object> topFiveCompDataHolder = new LinkedHashMap<>();

    List<Object> dataHolder = new LinkedList<>();
    List<Object> compCount = new ArrayList<>();
    Iterator<Entry<Object, Object>> entries = newdata.entrySet().iterator();
    int index = 0;
    while (entries.hasNext()) {
        Map<String, Object> tmpdata = new LinkedHashMap<>();
        Entry<Object, Object> entry = entries.next();
        if (index < 5) {
            compCount.add(entry.getValue());
            index++;
        } else if (index == 5) {
            compCount.add(entry.getValue());
            String[] parts = entry.getKey().toString().split("-");
            tmpdata.put("name", parts[1]);
            tmpdata.put("data", new LinkedList<Object>(compCount));
            HashMap<String, Object> ctypeCountMap = new LinkedHashMap<>();
            ctypeCountMap.putAll(tmpdata);
            dataHolder.add(ctypeCountMap);
            index = 0;
            compCount.clear();
            tmpdata.clear();
        }
    }
    topFiveCompDataHolder.put("year", dataHolderString);
    topFiveCompDataHolder.put("series", dataHolder);

    return topFiveCompDataHolder;
}