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:org.projectforge.web.humanresources.HRPlanningEventsProvider.java

License:Open Source License

private void putEvent(final HRPlanningEntryDO entry, final DateTime start, final String suffix,
        final int durationDays, final BigDecimal hours) {
    if (NumberHelper.isGreaterZero(hours) == false) {
        return;/*from  w  w  w  .j a  v  a  2s. c om*/
    }
    if (log.isDebugEnabled() == true) {
        log.debug("Date: " + start + ", hours=" + hours + ", duration: " + durationDays);
    }
    final Event event = new Event().setAllDay(true);
    event.setClassName(EVENT_CLASS_NAME);
    final String id = "" + entry.getId() + "-" + suffix;
    event.setId(id);
    event.setStart(start);
    if (durationDays > 0) {
        event.setEnd(start.plusDays(durationDays));
    } else {
        event.setEnd(start);
    }
    final StringBuffer buf = new StringBuffer();
    buf.append(NumberHelper.formatFraction2(hours)).append(parent.getString("calendar.unit.hour")).append(" ")
            .append(entry.getProjektNameOrStatus());
    if (StringUtils.isNotBlank(entry.getDescription()) == true) {
        buf.append(": ");
        if (durationDays > 2) {
            buf.append(StringUtils.abbreviate(entry.getDescription(), 100));
        } else if (durationDays > 1) {
            buf.append(StringUtils.abbreviate(entry.getDescription(), 50));
        } else {
            buf.append(StringUtils.abbreviate(entry.getDescription(), 20));
        }
    }
    event.setTitle(buf.toString());
    events.put(id, event);
}

From source file:org.projectforge.web.timesheet.TimesheetEventsProvider.java

License:Open Source License

/**
 * @see org.projectforge.web.calendar.MyFullCalendarEventsProvider#buildEvents(org.joda.time.DateTime, org.joda.time.DateTime)
 *//*from  w ww.  j av  a 2s.  c  o  m*/
@Override
protected void buildEvents(final DateTime start, final DateTime end) {
    totalDuration = 0;
    for (int i = 0; i < durationsPerDayOfMonth.length; i++) {
        durationsPerDayOfMonth[i] = 0;
    }
    for (int i = 0; i < durationsPerDayOfYear.length; i++) {
        durationsPerDayOfYear[i] = 0;
    }
    final Integer userId = calFilter.getTimesheetUserId();
    if (userId == null) {
        return;
    }
    breaksMap = new HashMap<String, TimesheetDO>();
    int breaksCounter = 0;
    final TimesheetFilter filter = new TimesheetFilter();
    filter.setUserId(userId);
    filter.setStartTime(start.toDate());
    filter.setStopTime(end.toDate());
    filter.setOrderType(OrderDirection.ASC);
    timesheets = timesheetDao.getList(filter);
    boolean longFormat = false;
    days = Days.daysBetween(start, end).getDays();
    if (days < 10) {
        // Week or day view:
        longFormat = true;
        month = null;
        firstDayOfMonth = null;
    } else {
        // Month view:
        final DateTime currentMonth = new DateTime(start.plusDays(10), PFUserContext.getDateTimeZone()); // Now we're definitely in the right
        // month.
        month = currentMonth.getMonthOfYear();
        firstDayOfMonth = currentMonth.withDayOfMonth(1);
    }
    if (CollectionUtils.isEmpty(timesheets) == false) {
        DateTime lastStopTime = null;
        for (final TimesheetDO timesheet : timesheets) {
            final DateTime startTime = new DateTime(timesheet.getStartTime(), PFUserContext.getDateTimeZone());
            final DateTime stopTime = new DateTime(timesheet.getStopTime(), PFUserContext.getDateTimeZone());
            if (stopTime.isBefore(start) == true || startTime.isAfter(end) == true) {
                // Time sheet doesn't match time period start - end.
                continue;
            }
            if (calFilter.isShowBreaks() == true) {
                if (lastStopTime != null && DateHelper.isSameDay(stopTime, lastStopTime) == true
                        && startTime.getMillis() - lastStopTime.getMillis() > 60000) {
                    // Show breaks between time sheets of one day (> 60s).
                    final Event breakEvent = new Event();
                    breakEvent.setEditable(false);
                    final String breakId = String.valueOf(++breaksCounter);
                    breakEvent.setClassName(BREAK_EVENT_CLASS_NAME).setId(breakId).setStart(lastStopTime)
                            .setEnd(startTime).setTitle(getString("timesheet.break"));
                    breakEvent.setTextColor("#666666").setBackgroundColor("#F9F9F9").setColor("#F9F9F9");
                    events.put(breakId, breakEvent);
                    final TimesheetDO breakTimesheet = new TimesheetDO().setStartDate(lastStopTime.toDate())
                            .setStopTime(startTime.getMillis());
                    breaksMap.put(breakId, breakTimesheet);
                }
                lastStopTime = stopTime;
            }
            final long duration = timesheet.getDuration();
            final MyEvent event = new MyEvent();
            final String id = "" + timesheet.getId();
            event.setClassName(EVENT_CLASS_NAME);
            event.setId(id);
            event.setStart(startTime);
            event.setEnd(stopTime);
            final String title = getTitle(timesheet);
            if (longFormat == true) {
                // Week or day view:
                event.setTitle(title + "\n" + getToolTip(timesheet) + "\n" + formatDuration(duration, false));
            } else {
                // Month view:
                event.setTitle(title);
            }
            if (month != null && startTime.getMonthOfYear() != month && stopTime.getMonthOfYear() != month) {
                // Display time sheets of other month as grey blue:
                event.setTextColor("#222222").setBackgroundColor("#ACD9E8").setColor("#ACD9E8");
            }
            events.put(id, event);
            if (month == null || startTime.getMonthOfYear() == month) {
                totalDuration += duration;
                addDurationOfDay(startTime.getDayOfMonth(), duration);
            }
            final int dayOfYear = startTime.getDayOfYear();
            addDurationOfDayOfYear(dayOfYear, duration);
            event.setTooltip(getString("timesheet"),
                    new String[][] { { title }, { timesheet.getLocation(), getString("timesheet.location") },
                            { KostFormatter.formatLong(timesheet.getKost2()), getString("fibu.kost2") },
                            { TaskFormatter.instance().getTaskPath(timesheet.getTaskId(), true,
                                    OutputType.PLAIN), getString("task") },
                            { timesheet.getDescription(), getString("description") } });
        }
    }
    if (calFilter.isShowStatistics() == true) {
        // Show statistics: duration of every day is shown as all day event.
        DateTime day = start;
        final Calendar cal = DateHelper.getCalendar();
        cal.setTime(start.toDate());
        final int numberOfDaysInYear = cal.getActualMaximum(Calendar.DAY_OF_YEAR);
        int paranoiaCounter = 0;
        do {
            if (++paranoiaCounter > 1000) {
                log.error(
                        "Paranoia counter exceeded! Dear developer, please have a look at the implementation of buildEvents.");
                break;
            }
            final int dayOfYear = day.getDayOfYear();
            final long duration = durationsPerDayOfYear[dayOfYear];
            final boolean firstDayOfWeek = day.getDayOfWeek() == PFUserContext.getJodaFirstDayOfWeek();
            if (firstDayOfWeek == false && duration == 0) {
                day = day.plusDays(1);
                continue;
            }
            final Event event = new Event().setAllDay(true);
            final String id = "s-" + (dayOfYear);
            event.setId(id);
            event.setStart(day);
            final String durationString = formatDuration(duration, false);
            if (firstDayOfWeek == true) {
                // Show week of year at top of first day of week.
                long weekDuration = 0;
                for (short i = 0; i < 7; i++) {
                    int d = dayOfYear + i;
                    if (d > numberOfDaysInYear) {
                        d -= numberOfDaysInYear;
                    }
                    weekDuration += durationsPerDayOfYear[d];
                }
                final StringBuffer buf = new StringBuffer();
                buf.append(getString("calendar.weekOfYearShortLabel")).append(DateHelper.getWeekOfYear(day));
                if (days > 1 && weekDuration > 0) {
                    // Show total sum of durations over all time sheets of current week (only in week and month view).
                    buf.append(": ").append(formatDuration(weekDuration, false));
                }
                if (duration > 0) {
                    buf.append(", ").append(durationString);
                }
                event.setTitle(buf.toString());
            } else {
                event.setTitle(durationString);
            }
            event.setTextColor("#666666").setBackgroundColor("#F9F9F9").setColor("#F9F9F9");
            event.setEditable(false);
            events.put(id, event);
            day = day.plusDays(1);
        } while (day.isAfter(end) == false);
    }
}

From source file:org.richfaces.examples.richrates.ChartBean.java

License:Open Source License

/**
 * Creates a data structure needed by chart component. It creates a set of points where X is date and Y is an
 * exchange rate.//w w w .  ja v a 2 s . c  o m
 * 
 * @return set of points for chart
 */
public void parseCurrencyData() {
    DateTime toDate = new DateTime(this.toDate);
    DateTime actualDate = new DateTime(fromDate);
    currency = new Currency();
    currency.setName(getSelectedCurrency());
    List<CurrencyRecord> records = new LinkedList<CurrencyRecord>();
    while (actualDate.compareTo(toDate) <= 0) {
        if (currencies.get(actualDate.toDate()) == null) {
            actualDate = actualDate.plusDays(1);
            continue;
        }
        String dayAndMonth = actualDate.toString("dd.MM");
        Number rate = currencies.get(actualDate.toDate()).get(selectedCurrency).doubleValue();
        records.add(new CurrencyRecord(dayAndMonth, rate));
        actualDate = actualDate.plusDays(1);
    }
    currency.setData(records);
}

From source file:org.roda.core.model.ModelService.java

private boolean isToIndex(String fileName, int daysToIndex) {
    boolean isToIndex = false;
    String fileNameWithoutExtension = fileName.replaceFirst(".log$", "");

    try {/*from  ww w. j ava 2s.  c o m*/
        DateTime dt = LOG_NAME_DATE_FORMAT.parseDateTime(fileNameWithoutExtension);

        if (dt.plusDays(daysToIndex + 1).isAfterNow()) {
            isToIndex = true;
        }

    } catch (IllegalArgumentException | UnsupportedOperationException e) {
        LOGGER.error("Could not parse log file name", e);
    }
    return isToIndex;
}

From source file:org.softdays.mandy.service.support.CalendarServiceImpl.java

License:Open Source License

@Override
public DataGridDto getDataGridOfTheMonth(final DateTime date) {
    DateTime currentDate = this.getFirstMondayOfMonth(date);
    final DateTime end = this.getFirstSundayAfterEndOfMonth(date);
    final DataGridDto dataGrid = new DataGridDto(date.toDate());
    WeekDto week = dataGrid.createWeek();
    while (!currentDate.equals(end)) {
        if (!this.isEndOfWeek(currentDate)) {
            // ici on est sr de devoir insrer un jour ouvr
            if (week.isCompleted()) {
                // c'est bien ici qu'il faut grer les crations de semaines
                week = dataGrid.createWeek();
            }/*w w w .ja  v  a 2  s  .c o m*/
            week.createDay(currentDate, this.getDateStatus(currentDate));
        }
        currentDate = currentDate.plusDays(1);
    }
    return dataGrid;
}

From source file:org.softdays.mandy.service.support.CalendarServiceImpl.java

License:Open Source License

@Override
public DateTime getFirstMondayOfMonth(final DateTime givenDate) {
    DateTime date = givenDate.dayOfMonth().withMinimumValue();
    while (!this.isMonday(date)) {
        date = date.plusDays(1);
    }/*from  w ww. jav a 2s . com*/

    return date;
}

From source file:org.softdays.mandy.service.support.CalendarServiceImpl.java

License:Open Source License

@Override
public DateTime getFirstSundayAfterEndOfMonth(final DateTime givenDate) {
    DateTime date = givenDate.dayOfMonth().withMaximumValue();
    while (date.getDayOfWeek() != DateTimeConstants.SUNDAY) {
        date = date.plusDays(1);
    }/*from w w  w .ja  v a  2  s . c o  m*/

    return date;
}

From source file:org.softdays.mandy.service.support.SchoolHolidayServiceImpl.java

License:Open Source License

/**
 * Il ne faut pas inclure les bornes.// w w  w.ja  v a2s .c  om
 */
private void addRange(final DateTime start, final DateTime end) {
    DateTime date = start.plusDays(1); // J+1
    while (!date.equals(end)) {
        this.schoolHolidays.add(date);
        date = date.plusDays(1);
    }
}

From source file:org.springframework.analytics.metrics.memory.InMemoryAggregateCounter.java

License:Apache License

public AggregateCounter getCounts(Interval interval, AggregateCounterResolution resolution) {
    DateTime start = interval.getStart();
    DateTime end = interval.getEnd();
    Chronology c = interval.getChronology();

    long[] counts;
    if (resolution == AggregateCounterResolution.minute) {
        List<long[]> days = accumulateDayCounts(minuteCountsByDay, start, end, 60 * 24);

        counts = MetricUtils.concatArrays(days, interval.getStart().getMinuteOfDay(),
                interval.toPeriod().toStandardMinutes().getMinutes() + 1);
    } else if (resolution == AggregateCounterResolution.hour) {
        List<long[]> days = accumulateDayCounts(hourCountsByDay, start, end, 24);

        counts = MetricUtils.concatArrays(days, interval.getStart().getHourOfDay(),
                interval.toPeriod().toStandardHours().getHours() + 1);
    } else if (resolution == AggregateCounterResolution.day) {
        DateTime startDay = new DateTime(c.dayOfYear().roundFloor(start.getMillis()));
        DateTime endDay = new DateTime(c.dayOfYear().roundFloor(end.plusDays(1).getMillis()));
        int nDays = Days.daysBetween(startDay, endDay).getDays();
        DateTime cursor = new DateTime(c.year().roundFloor(interval.getStartMillis()));
        List<long[]> yearDays = new ArrayList<long[]>();
        DateTime endYear = new DateTime(c.year().roundCeiling(end.getMillis()));

        while (cursor.isBefore(endYear)) {
            long[] dayCounts = dayCountsByYear.get(cursor.getYear());
            if (dayCounts == null) {
                // Querying where we have no data
                dayCounts = new long[daysInYear(cursor.getYear())];
            }/*from w w w. jav  a 2s  .  co  m*/
            yearDays.add(dayCounts);
            cursor = cursor.plusYears(1);
        }

        counts = MetricUtils.concatArrays(yearDays, startDay.getDayOfYear() - 1, nDays);

    } else if (resolution == AggregateCounterResolution.month) {
        DateTime startMonth = new DateTime(c.monthOfYear().roundFloor(interval.getStartMillis()));
        DateTime endMonth = new DateTime(c.monthOfYear().roundFloor(end.plusMonths(1).getMillis()));
        int nMonths = Months.monthsBetween(startMonth, endMonth).getMonths();
        DateTime cursor = new DateTime(c.year().roundFloor(interval.getStartMillis()));
        List<long[]> yearMonths = new ArrayList<long[]>();
        DateTime endYear = new DateTime(c.year().roundCeiling(end.getMillis()));

        while (cursor.isBefore(endYear)) {
            long[] monthCounts = monthCountsByYear.get(cursor.getYear());
            if (monthCounts == null) {
                monthCounts = new long[12];
            }
            yearMonths.add(monthCounts);
            cursor = cursor.plusYears(1);
        }

        counts = MetricUtils.concatArrays(yearMonths, startMonth.getMonthOfYear() - 1, nMonths);
    } else if (resolution == AggregateCounterResolution.year) {
        DateTime startYear = new DateTime(interval.getStart().getYear(), 1, 1, 0, 0);
        DateTime endYear = new DateTime(end.getYear() + 1, 1, 1, 0, 0);
        int nYears = Years.yearsBetween(startYear, endYear).getYears();
        counts = new long[nYears];

        for (int i = 0; i < nYears; i++) {
            long[] monthCounts = monthCountsByYear.get(startYear.plusYears(i).getYear());
            counts[i] = MetricUtils.sum(monthCounts);
        }

    } else {
        throw new IllegalStateException("Shouldn't happen. Unhandled resolution: " + resolution);
    }
    return new AggregateCounter(this.name, interval, counts, resolution);
}

From source file:org.springframework.analytics.metrics.memory.InMemoryAggregateCounter.java

License:Apache License

private static List<long[]> accumulateDayCounts(Map<Integer, long[]> fromDayCounts, DateTime start,
        DateTime end, int subSize) {
    List<long[]> days = new ArrayList<long[]>();
    Duration step = Duration.standardDays(1);
    long[] emptySubArray = new long[subSize];
    end = end.plusDays(1); // Need to account for an interval which crosses days

    for (DateTime now = start; now.isBefore(end); now = now.plus(step)) {
        int countsByDayKey = now.getYear() * 1000 + now.getDayOfYear();
        long[] dayCounts = fromDayCounts.get(countsByDayKey);

        if (dayCounts == null) {
            // Use an empty array if we don't have data
            dayCounts = emptySubArray;/*ww  w .j  av a  2s . c  om*/
        }
        days.add(dayCounts);
    }
    return days;
}