Example usage for org.joda.time DateTime plusDays

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

Introduction

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

Prototype

public DateTime plusDays(int days) 

Source Link

Document

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

Usage

From source file:com.cronutils.model.time.ExecutionTime.java

License:Apache License

/**
 * If date is not match, will return next closest match.
 * If date is match, will return this date.
 * @param date - reference DateTime instance - never null;
 * @return DateTime instance, never null. Value obeys logic specified above.
 * @throws NoSuchValueException/*from   w ww . jav  a 2s  .c o  m*/
 */
DateTime nextClosestMatch(DateTime date) throws NoSuchValueException {
    List<Integer> year = yearsValueGenerator.generateCandidates(date.getYear(), date.getYear());
    TimeNode days = null;
    int lowestMonth = months.getValues().get(0);
    int lowestHour = hours.getValues().get(0);
    int lowestMinute = minutes.getValues().get(0);
    int lowestSecond = seconds.getValues().get(0);

    NearestValue nearestValue;
    DateTime newDate;
    if (year.isEmpty()) {
        int newYear = yearsValueGenerator.generateNextValue(date.getYear());
        days = generateDays(cronDefinition, new DateTime(newYear, lowestMonth, 1, 0, 0));
        return initDateTime(yearsValueGenerator.generateNextValue(date.getYear()), lowestMonth,
                days.getValues().get(0), lowestHour, lowestMinute, lowestSecond, date.getZone());
    }
    if (!months.getValues().contains(date.getMonthOfYear())) {
        nearestValue = months.getNextValue(date.getMonthOfYear(), 0);
        int nextMonths = nearestValue.getValue();
        if (nearestValue.getShifts() > 0) {
            newDate = new DateTime(date.getYear(), 1, 1, 0, 0, 0, date.getZone())
                    .plusYears(nearestValue.getShifts());
            return nextClosestMatch(newDate);
        }
        if (nearestValue.getValue() < date.getMonthOfYear()) {
            date = date.plusYears(1);
        }
        days = generateDays(cronDefinition, new DateTime(date.getYear(), nextMonths, 1, 0, 0));
        return initDateTime(date.getYear(), nextMonths, days.getValues().get(0), lowestHour, lowestMinute,
                lowestSecond, date.getZone());
    }
    days = generateDays(cronDefinition, date);
    if (!days.getValues().contains(date.getDayOfMonth())) {
        nearestValue = days.getNextValue(date.getDayOfMonth(), 0);
        if (nearestValue.getShifts() > 0) {
            newDate = new DateTime(date.getYear(), date.getMonthOfYear(), 1, 0, 0, 0, date.getZone())
                    .plusMonths(nearestValue.getShifts());
            return nextClosestMatch(newDate);
        }
        if (nearestValue.getValue() < date.getDayOfMonth()) {
            date = date.plusMonths(1);
        }
        return initDateTime(date.getYear(), date.getMonthOfYear(), nearestValue.getValue(), lowestHour,
                lowestMinute, lowestSecond, date.getZone());
    }
    if (!hours.getValues().contains(date.getHourOfDay())) {
        nearestValue = hours.getNextValue(date.getHourOfDay(), 0);
        int nextHours = nearestValue.getValue();
        if (nearestValue.getShifts() > 0) {
            newDate = new DateTime(date.getYear(), date.getMonthOfYear(), date.getDayOfMonth(), 0, 0, 0,
                    date.getZone()).plusDays(nearestValue.getShifts());
            return nextClosestMatch(newDate);
        }
        if (nearestValue.getValue() < date.getHourOfDay()) {
            date = date.plusDays(1);
        }
        return initDateTime(date.getYear(), date.getMonthOfYear(), date.getDayOfMonth(), nextHours,
                lowestMinute, lowestSecond, date.getZone());
    }
    if (!minutes.getValues().contains(date.getMinuteOfHour())) {
        nearestValue = minutes.getNextValue(date.getMinuteOfHour(), 0);
        int nextMinutes = nearestValue.getValue();
        if (nearestValue.getShifts() > 0) {
            newDate = new DateTime(date.getYear(), date.getMonthOfYear(), date.getDayOfMonth(),
                    date.getHourOfDay(), 0, 0, date.getZone()).plusHours(nearestValue.getShifts());
            return nextClosestMatch(newDate);
        }
        if (nearestValue.getValue() < date.getMinuteOfHour()) {
            date = date.plusHours(1);
        }
        return initDateTime(date.getYear(), date.getMonthOfYear(), date.getDayOfMonth(), date.getHourOfDay(),
                nextMinutes, lowestSecond, date.getZone());
    }
    if (!seconds.getValues().contains(date.getSecondOfMinute())) {
        nearestValue = seconds.getNextValue(date.getSecondOfMinute(), 0);
        int nextSeconds = nearestValue.getValue();
        if (nearestValue.getShifts() > 0) {
            newDate = new DateTime(date.getYear(), date.getMonthOfYear(), date.getDayOfMonth(),
                    date.getHourOfDay(), date.getMinuteOfHour(), 0, date.getZone())
                            .plusMinutes(nearestValue.getShifts());
            return nextClosestMatch(newDate);
        }
        if (nearestValue.getValue() < date.getSecondOfMinute()) {
            date = date.plusMinutes(1);
        }
        return initDateTime(date.getYear(), date.getMonthOfYear(), date.getDayOfMonth(), date.getHourOfDay(),
                date.getMinuteOfHour(), nextSeconds, date.getZone());
    }
    return date;
}

From source file:com.dz.common.dataimport3.ColdPlayer.java

private void importData(List<String> carNums, String feeType, BigDecimal fee) {
    for (String carNum : carNums) {
        try {/*  w w w .j  av a  2 s  . c  o  m*/
            Vehicle fuck_v = new Vehicle();
            fuck_v.setLicenseNum(carNum);
            Vehicle real_v = vehicleService.selectByLicenseNum(fuck_v);
            Contract contract = contractService.selectByCarId(real_v.getCarframeNum());
            VehicleApproval va = vehicleApprovalService.queryVehicleApprovalByContractId(contract.getId());
            Date startTime = va.getOperateCardDate();
            DateTime st = new DateTime(startTime);
            Date endTime = contract.getContractEndDate();
            BatchPlan bp = new BatchPlan();
            bp.setFeeType(feeType);
            bp.setFee(fee);
            bp.setStartTime(st.plusDays(3).toDate());
            bp.setEndTime(endTime);
            List<Integer> cids = new ArrayList<>();
            cids.add(contract.getId());
            bp.setContractIdList(cids);
            chargeService.addBatchPlan(bp, false);
        } catch (Exception e) {
            System.out.println("Error at:" + carNum);
            e.printStackTrace();
        }
    }
}

From source file:com.ehdev.chronos.lib.Chronos.java

License:Open Source License

public static DateTime getDateFromStartOfPayPeriod(DateTime StartOfPP, DateTime date) {

    DateTime newDate;/*  w  w w  .  jav  a2 s .c  o  m*/
    DateTimeZone startZone = StartOfPP.getZone();
    DateTimeZone endZone = date.getZone();
    long dateTime = date.getMillis() - StartOfPP.getMillis();

    long offset = endZone.getOffset(date) - startZone.getOffset(StartOfPP);
    //System.out.println("offset: " + offset);
    dateTime += offset;

    //System.out.println("millis diff: " + (dateTime) );
    int days = (int) (dateTime / 1000 / 60 / 60 / 24);
    newDate = StartOfPP.plusDays(days);
    //System.out.println("Days to add: " + days);

    return newDate;
}

From source file:com.ehdev.chronos.lib.Chronos.java

License:Open Source License

public List<Punch> getPunchesByJobAndDate(Job jobId, DateTime date) {
    List<Punch> punches = new LinkedList<Punch>();

    // instantiate the DAO to handle Account with String id
    try {/*from  ww w .j a v  a2  s . com*/
        Dao<Punch, String> punchDao = getPunchDao();
        Dao<Task, String> taskDAO = getTaskDao();
        Dao<Job, String> jobDAO = getJobDao();

        //Period prd = new Period(jobId.getStartOfPayPeriod(), date);
        //Duration dur = new Duration(jobId.getStartOfPayPeriod(), date);
        DateTime startOfDay = date;
        //if(jobId.getStartOfPayPeriod().isBefore(date))
        //    startOfDay = jobId.getStartOfPayPeriod().plusDays(prd.toStandardDays().get(DurationFieldType.days()));
        //else
        //    startOfDay = jobId.getStartOfPayPeriod().minusDays(prd.toStandardDays().get(DurationFieldType.days()));
        //DateTime startOfDay = jobId.getStartOfPayPeriod().plusDays(displacementInDays);

        DateTime endOfDay = startOfDay.plusDays(1);

        if (enableLog)
            Log.d(TAG, "Start of Day: " + startOfDay.getMillis());
        if (enableLog)
            Log.d(TAG, "End of Day: " + endOfDay.getMillis());

        QueryBuilder<Punch, String> queryBuilder = punchDao.queryBuilder();
        queryBuilder.where().eq(Job.JOB_FIELD_NAME, jobId.getID()).and().between(Punch.TIME_OF_PUNCH,
                startOfDay.getMillis(), endOfDay.getMillis());

        PreparedQuery<Punch> preparedQuery = queryBuilder.prepare();

        punches = punchDao.query(preparedQuery);
        if (enableLog)
            Log.d(TAG, "Punches for this day: " + punches.size());
        for (Punch work : punches) {
            taskDAO.refresh(work.getTask());
            jobDAO.refresh(work.getTask().getJob());
            jobDAO.refresh(work.getJob());
            //if(enableLog) Log.d(TAG, "in loop Pay Rate: " + work.getJob().getPayRate());

        }
        Collections.sort(punches);

    } catch (SQLException e) {
        e.printStackTrace();
        Log.e(TAG, e.getMessage());
    }

    //Log.d(TAG, "Number of punches: " + punches.size());
    return punches;
}

From source file:com.ehdev.chronos.lib.Chronos.java

License:Open Source License

public void dropAndTest() {
    try {//  w  ww. j av  a 2s.co  m

        // instantiate the DAO to handle Account with String id
        Dao<Punch, String> punchDao = getPunchDao();
        Dao<Task, String> taskDAO = getTaskDao();
        Dao<Job, String> jobDAO = getJobDao();
        Dao<Note, String> noteDAO = getNoteDao();

        List<Task> tasks = taskDAO.queryForAll();
        Job currentJob = jobDAO.queryForAll().get(0);

        DateTime iTime = new DateTime();
        Random rand = new Random();
        DateTime tempTime = null;

        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 5; j++) {

                tempTime = iTime.minusHours(j);
                tempTime = tempTime.minusMinutes(rand.nextInt() % 60);
                Punch temp = new Punch(currentJob, tasks.get(0), tempTime);

                Note newNote = new Note(tempTime, currentJob, "Note number " + String.valueOf(j + 1));

                noteDAO.create(newNote);
                punchDao.create(temp);
            }

            tempTime = tempTime.minusMinutes(rand.nextInt() % 60);
            punchDao.create(
                    new Punch(currentJob, tasks.get((int) (Math.random() * 100) % tasks.size()), tempTime));

            iTime = iTime.plusDays(1);
        }

    } catch (SQLException e) {
        Log.e(TAG, e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
    }
}

From source file:com.ehdev.chronos.lib.types.holders.PayPeriodHolder.java

License:Open Source License

/**
 * Will do the calculations for the start and end of the process
 *///from w ww . ja v a  2 s .com
public void generate() {
    //Get the start and end of pay period
    DateTime startOfPP = gJob.getStartOfPayPeriod();
    gDuration = gJob.getDuration();
    DateTime endOfPP = DateTime.now(); //Today

    long duration = endOfPP.getMillis() - startOfPP.getMillis();

    DateTimeZone startZone = startOfPP.getZone();
    DateTimeZone endZone = endOfPP.getZone();

    long offset = endZone.getOffset(endOfPP) - startZone.getOffset(startOfPP);

    int weeks = (int) ((duration + offset) / 1000 / 60 / 60 / 24 / 7);

    /*
    System.out.println("end of pp: " + endOfPP);
    System.out.println("start of pp: " + startOfPP);
    System.out.println("dur: " + duration);
    System.out.println("weeks diff: " + weeks);
    */

    switch (gDuration) {
    case ONE_WEEK:
        //weeks = weeks;
        startOfPP = startOfPP.plusWeeks(weeks);
        endOfPP = startOfPP.plusWeeks(1);
        break;
    case TWO_WEEKS:
        weeks = weeks / 2;
        startOfPP = startOfPP.plusWeeks(weeks * 2);
        endOfPP = startOfPP.plusWeeks(2);
        break;
    case THREE_WEEKS:
        weeks = weeks / 3;
        startOfPP = startOfPP.plusWeeks(weeks * 3);
        endOfPP = startOfPP.plusWeeks(3);
        break;
    case FOUR_WEEKS:
        weeks = weeks / 4;
        startOfPP = startOfPP.plusWeeks(weeks * 4);
        endOfPP = startOfPP.plusWeeks(4);
        break;
    case FULL_MONTH:
        //in this case, endOfPP is equal to now
        startOfPP = DateMidnight.now().toDateTime().withDayOfMonth(1);
        endOfPP = startOfPP.plusMonths(1);

        break;
    case FIRST_FIFTEENTH:
        DateTime now = DateTime.now();
        if (now.getDayOfMonth() >= 15) {
            startOfPP = now.withDayOfMonth(15);
            endOfPP = startOfPP.plusDays(20).withDayOfMonth(1);
        } else {
            startOfPP = now.withDayOfMonth(1);
            endOfPP = now.withDayOfMonth(15);
        }
        break;
    default:
        break;
    }

    if (startOfPP.isAfter(DateTime.now())) {
        startOfPP = startOfPP.minusWeeks(getDays() / 7);
        endOfPP = endOfPP.minusWeeks(getDays() / 7);
    }

    gStartOfPP = startOfPP;
    gEndOfPP = endOfPP;
}

From source file:com.ehdev.chronos.lib.types.holders.PunchTable.java

License:Open Source License

private void createTable(Job inJob, int days, DateTime start) {
    listOfDays = new LinkedList<DateTime>();
    gMap = new HashMap<DateTime, List<Punch>>();
    gPayPeriod = new PayPeriodHolder(inJob);

    for (int i = 0; i < days; i++) {

        DateTime key = start.plusDays(i);
        LinkedList<Punch> list = new LinkedList<Punch>();
        gMap.put(key, list);//from  www . jav a  2  s  .c om
        listOfDays.add(key);
        //System.out.println("Days: " + key);
    }
}

From source file:com.epam.ta.reportportal.core.widget.content.StatisticBasedContentLoader.java

License:Open Source License

/**
 * Create ranged empty timeline billet// ww w .j a  va2 s.co m
 * 
 * @param base
 * @param period
 * @return
 */
private Map<String, ChartObject> buildRange(List<ChartObject> base, Period period) {
    final LongSummaryStatistics statistics = base.stream()
            .mapToLong(object -> Long.valueOf(object.getStartTime())).summaryStatistics();
    final DateTime start = new DateTime(statistics.getMin());
    final DateTime end = new DateTime(statistics.getMax());
    DateTime intermediate = start;
    final LinkedHashMap<String, ChartObject> map = new LinkedHashMap<>();
    if (base.isEmpty())
        return map;
    while (intermediate.isBefore(end)) {
        map.put(intermediate.toString(DATE_PATTERN), createChartObject(base.get(0)));
        switch (period) {
        case DAY:
            intermediate = intermediate.plusDays(1);
            break;
        case WEEK:
            intermediate = intermediate.plusDays(1);
            break;
        case MONTH:
            intermediate = intermediate.plusMonths(1);
            break;
        }
    }
    map.put(end.toString(DATE_PATTERN), createChartObject(base.get(0)));
    return map;
}

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  www . j  a  v  a2 s  . c o  m
        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.esofthead.mycollab.common.service.ibatis.TimelineTrackingServiceImpl.java

License:Open Source License

private List<Date> boundDays(DateTime start, DateTime end) {
    Duration duration = new Duration(start, end);
    long days = duration.getStandardDays();
    List<Date> dates = new ArrayList<>();
    //Will try to get from cache values from the end date to (startdate - 1)
    for (int i = 0; i <= days; i++) {
        dates.add(start.plusDays(i).toDate());
    }//from www  .  ja  va2 s  .  c  o m
    return dates;
}