Example usage for org.joda.time DateTime minusDays

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

Introduction

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

Prototype

public DateTime minusDays(int days) 

Source Link

Document

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

Usage

From source file:com.cronutils.model.time.generator.OnDayOfWeekValueGenerator.java

License:Apache License

private int generateLValues(On on, int year, int month) throws NoSuchValueException {
    int lastDoM = new DateTime(year, month, 1, 1, 1).dayOfMonth().getMaximumValue();
    DateTime lastDoMDateTime = new DateTime(year, month, lastDoM, 1, 1);
    int dowForLastDoM = lastDoMDateTime.getDayOfWeek();//1-7
    int requiredDoW = ConstantsMapper.weekDayMapping(mondayDoWValue, ConstantsMapper.JODATIME_WEEK_DAY,
            on.getTime().getValue());//to normalize to joda-time value
    int dowDiff = dowForLastDoM - requiredDoW;

    if (dowDiff == 0) {
        return lastDoMDateTime.dayOfMonth().get();
    }//from w w  w  .java  2 s  .  co  m
    if (dowDiff < 0) {
        return lastDoMDateTime.minusDays(dowForLastDoM + (7 - requiredDoW)).dayOfMonth().get();
    }
    if (dowDiff > 0) {
        return lastDoMDateTime.minusDays(dowDiff).dayOfMonth().get();
    }
    throw new NoSuchValueException();
}

From source file:com.datastax.sampledata.CreateSSTables.java

private static Date randomDateInLastNYears(int years) {

    DateTime dateTime = new DateTime();
    dateTime = dateTime.minusYears(new Double(Math.random() * years).intValue());
    dateTime = dateTime.minusMonths(new Double(Math.random() * 12).intValue());
    dateTime = dateTime.minusDays(new Double(Math.random() * 30).intValue());

    dateTime = dateTime.minusHours(new Double(Math.random() * 24).intValue());
    dateTime = dateTime.minusMinutes(new Double(Math.random() * 60).intValue());
    dateTime = dateTime.minusSeconds(new Double(Math.random() * 60).intValue());

    return dateTime.toDate();
}

From source file:com.davis.bluefolder.BlueUtils.java

public static String contructDatesForSearch(String start, String end) {
    DateTimeFormatter fmt = DateTimeFormat.forPattern("MM-dd-yyyy hh:mma");
    DateTimeZone timeZone = DateTimeZone.forID("America/New_York"); // Specify or else the JVM's default will apply.
    DateTime dateTime = new DateTime(new java.util.Date(), timeZone); // Today's Date
    DateTime pastDate = dateTime.minusDays(14); // 2 weeks ago

    String endDate = null;// w  w  w. jav  a 2s.c o  m
    String startDate = null;
    if (start != null && !start.trim().equalsIgnoreCase("")) {
        if (end != null && !end.trim().equalsIgnoreCase("")) {
            startDate = fmt.parseDateTime(start).toString();
            endDate = fmt.parseDateTime(end).toString();
        } else {
            endDate = fmt.print(dateTime);
            startDate = fmt.print(pastDate);
        }
    } else {
        endDate = fmt.print(dateTime);
        startDate = fmt.print(pastDate);
    }

    //dateTimeClosed
    String date = " <dateRange dateField=\"dateTimeCreated\">" + "<startDate>" + startDate + "</startDate>"
            + "<endDate>" + endDate + "</endDate>" + "</dateRange>";

    return date;

}

From source file:com.esofthead.mycollab.common.service.ibatis.TimelineTrackingServiceImpl.java

License:Open Source License

@Override
public Map<String, List<GroupItem>> findTimelineItems(String fieldGroup, List<String> groupVals, Date start,
        Date end, TimelineTrackingSearchCriteria criteria) {
    try {//from  w w  w  .  j ava  2s .com
        DateTime startDate = new DateTime(start);
        final DateTime endDate = new DateTime(end);
        if (startDate.isAfter(endDate)) {
            throw new UserInvalidInputException("Start date must be greater than end date");
        }
        List<Date> dates = boundDays(startDate, endDate.minusDays(1));
        Map<String, List<GroupItem>> items = new HashMap<>();
        criteria.setFieldgroup(StringSearchField.and(fieldGroup));
        List<GroupItem> cacheTimelineItems = timelineTrackingCachingMapperExt.findTimelineItems(groupVals,
                dates, criteria);

        DateTime calculatedDate = startDate.toDateTime();
        if (cacheTimelineItems.size() > 0) {
            GroupItem item = cacheTimelineItems.get(cacheTimelineItems.size() - 1);
            String dateValue = item.getGroupname();
            calculatedDate = DateTime.parse(dateValue, DateTimeFormat.forPattern("yyyy-MM-dd"));

            for (GroupItem map : cacheTimelineItems) {
                String groupVal = map.getGroupid();
                Object obj = items.get(groupVal);
                if (obj == null) {
                    List<GroupItem> itemLst = new ArrayList<>();
                    itemLst.add(map);
                    items.put(groupVal, itemLst);
                } else {
                    List<GroupItem> itemLst = (List<GroupItem>) obj;
                    itemLst.add(map);
                }
            }
        }

        dates = boundDays(calculatedDate.plusDays(1), endDate);
        if (dates.size() > 0) {
            boolean isValidForBatchSave = true;
            final String type = criteria.getType().getValue();
            SetSearchField<Integer> extraTypeIds = criteria.getExtraTypeIds();
            Integer tmpExtraTypeId = null;
            if (extraTypeIds != null) {
                if (extraTypeIds.getValues().size() == 1) {
                    tmpExtraTypeId = extraTypeIds.getValues().iterator().next();
                } else {
                    isValidForBatchSave = false;
                }
            }
            final Integer extraTypeId = tmpExtraTypeId;

            final List<Map> timelineItems = timelineTrackingMapperExt.findTimelineItems(groupVals, dates,
                    criteria);
            if (isValidForBatchSave) {
                final Integer sAccountId = (Integer) criteria.getSaccountid().getValue();
                final String itemFieldGroup = criteria.getFieldgroup().getValue();
                JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

                final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
                final List<Map> filterCollections = new ArrayList<>(
                        Collections2.filter(timelineItems, new Predicate<Map>() {
                            @Override
                            public boolean apply(Map input) {
                                String dateStr = (String) input.get("groupname");
                                DateTime dt = formatter.parseDateTime(dateStr);
                                return !dt.equals(endDate);
                            }
                        }));
                jdbcTemplate.batchUpdate(
                        "INSERT INTO `s_timeline_tracking_cache`(type, fieldval,extratypeid,sAccountId,"
                                + "forDay, fieldgroup,count) VALUES(?,?,?,?,?,?,?)",
                        new BatchPreparedStatementSetter() {
                            @Override
                            public void setValues(PreparedStatement preparedStatement, int i)
                                    throws SQLException {
                                Map item = filterCollections.get(i);
                                preparedStatement.setString(1, type);
                                String fieldVal = (String) item.get("groupid");
                                preparedStatement.setString(2, fieldVal);
                                preparedStatement.setInt(3, extraTypeId);
                                preparedStatement.setInt(4, sAccountId);
                                String dateStr = (String) item.get("groupname");
                                DateTime dt = formatter.parseDateTime(dateStr);
                                preparedStatement.setDate(5, new java.sql.Date(dt.toDate().getTime()));
                                preparedStatement.setString(6, itemFieldGroup);
                                int value = ((BigDecimal) item.get("value")).intValue();
                                preparedStatement.setInt(7, value);
                            }

                            @Override
                            public int getBatchSize() {
                                return filterCollections.size();
                            }
                        });
            }

            for (Map map : timelineItems) {
                String groupVal = (String) map.get("groupid");
                GroupItem item = new GroupItem();
                item.setValue(((BigDecimal) map.get("value")).doubleValue());
                item.setGroupid((String) map.get("groupid"));
                item.setGroupname((String) map.get("groupname"));
                Object obj = items.get(groupVal);
                if (obj == null) {
                    List<GroupItem> itemLst = new ArrayList<>();
                    itemLst.add(item);
                    items.put(groupVal, itemLst);
                } else {
                    List<GroupItem> itemLst = (List<GroupItem>) obj;
                    itemLst.add(item);
                }
            }
        }

        return items;
    } catch (Exception e) {
        LOG.error("Error", e);
        return null;
    }
}

From source file:com.example.Database.java

public String getDate(int daysago) {
    DateTime date = new DateTime();
    DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd");
    date = date.minusDays(daysago);
    return fmt.print(date);
}

From source file:com.example.getstarted.util.DatastoreSessionFilter.java

License:Apache License

@Override
public void init(FilterConfig config) throws ServletException {
    // initialize local copy of datastore session variables

    datastore = DatastoreServiceFactory.getDatastoreService();
    // Delete all sessions unmodified for over two days
    DateTime dt = DateTime.now(DateTimeZone.UTC);
    Query query = new Query(SESSION_KIND).setFilter(new FilterPredicate("lastModified",
            FilterOperator.LESS_THAN_OR_EQUAL, dt.minusDays(2).toString(DTF)));
    Iterator<Entity> results = datastore.prepare(query).asIterator();
    while (results.hasNext()) {
        Entity stateEntity = results.next();
        datastore.delete(stateEntity.getKey());
    }//from   w  w  w . ja  va2  s. c o m
}

From source file:com.facebook.presto.atop.AtopSplitManager.java

License:Apache License

@Override
public ConnectorSplitSource getSplits(ConnectorTransactionHandle transactionHandle, ConnectorSession session,
        ConnectorTableLayoutHandle layoutHandle) {
    AtopTableLayoutHandle handle = checkType(layoutHandle, AtopTableLayoutHandle.class, "layoutHandle");

    AtopTableHandle table = handle.getTableHandle();

    List<ConnectorSplit> splits = new ArrayList<>();
    DateTime end = DateTime.now().withZone(timeZone);
    for (Node node : nodeManager.getActiveDatasourceNodes(connectorId.getId())) {
        DateTime start = end.minusDays(maxHistoryDays - 1).withTimeAtStartOfDay();
        while (start.isBefore(end)) {
            DateTime splitEnd = start.withTime(23, 59, 59, 999);
            Domain splitDomain = Domain.create(
                    ValueSet.ofRanges(//w  w  w  . ja  va2s  .c o m
                            Range.range(TIMESTAMP, start.getMillis(), true, splitEnd.getMillis(), true)),
                    false);
            if (handle.getStartTimeConstraint().overlaps(splitDomain)
                    && handle.getEndTimeConstraint().overlaps(splitDomain)) {
                splits.add(new AtopSplit(table.getTable(), node.getHostAndPort(), start));
            }
            start = start.plusDays(1).withTimeAtStartOfDay();
        }
    }

    return new FixedSplitSource(connectorId.getId(), splits);
}

From source file:com.github.markserrano.jsonquery.jpa.util.DateTimeUtil.java

License:Apache License

public static Map<String, DateTime> getYesterdaySpan() {
    DateTime now = new DateTime();

    DateTime from = now.minusDays(1).minusHours(now.getHourOfDay()).minusMinutes(now.getMinuteOfHour())
            .minusSeconds(now.getSecondOfMinute()).minusMillis(now.getMillisOfSecond());

    DateTime to = from.plusHours(23).plusMinutes(59).plusSeconds(59);

    Map<String, DateTime> map = new HashMap<String, DateTime>();
    map.put("from", from);
    map.put("to", to);

    return map;//from w  w  w.jav  a 2 s .  c  o m
}

From source file:com.google.api.ads.adwords.awreporting.model.entities.dateranges.Last14DaysDateRangeHandler.java

License:Open Source License

@Override
public DateTime retrieveDateStart(DateTime date) {
    return date.minusDays(14);
}

From source file:com.google.api.ads.adwords.awreporting.model.entities.dateranges.Last30DaysDateRangeHandler.java

License:Open Source License

@Override
public DateTime retrieveDateStart(DateTime date) {
    return date.minusDays(30);
}