Example usage for org.joda.time Period getDays

List of usage examples for org.joda.time Period getDays

Introduction

In this page you can find the example usage for org.joda.time Period getDays.

Prototype

public int getDays() 

Source Link

Document

Gets the days field part of the period.

Usage

From source file:org.projectforge.web.calendar.MyEvent.java

License:Open Source License

public String getDuration() {
    if (duration != null) {
        return duration;
    }// w  w  w.  j  a v a  2 s . c  o  m
    final Period period = new Period(this.getStart(), this.getEnd());
    int days = period.getDays();
    if (isAllDay() == true) {
        ++days;
    }
    final int hours = period.getHours();
    final int minutes = period.getMinutes();
    final StringBuffer buf = new StringBuffer();
    if (days > 0) { // days
        buf.append(days).append(PFUserContext.getLocalizedString("calendar.unit.day")).append(" ");
    }
    if (isAllDay() == false) {
        buf.append(hours).append(":"); // hours
        if (minutes < 10) {
            buf.append("0");
        }
        buf.append(minutes);
    }
    duration = buf.toString();
    return duration;
}

From source file:org.projectforge.web.teamcal.event.MyWicketEvent.java

License:Open Source License

public String getDuration() {
    if (duration != null) {
        return duration;
    }// w  w w.  j av  a2  s.  c  o  m
    final Period period = new Period(this.getStart(), this.getEnd());
    int days = period.getDays();
    if (isAllDay() == true) {
        ++days;
    }
    final int hours = period.getHours();
    final int minutes = period.getMinutes();
    final StringBuffer buf = new StringBuffer();
    if (days > 0) { // days
        buf.append(days).append(ThreadLocalUserContext.getLocalizedString("calendar.unit.day")).append(" ");
    }
    if (isAllDay() == false) {
        buf.append(hours).append(":"); // hours
        if (minutes < 10) {
            buf.append("0");
        }
        buf.append(minutes);
    }
    duration = buf.toString();
    return duration;
}

From source file:org.projectforge.web.teamcal.event.TeamCalEventProvider.java

License:Open Source License

/**
 * @see org.projectforge.web.calendar.MyFullCalendarEventsProvider#buildEvents(org.joda.time.DateTime,
 *      org.joda.time.DateTime)//from   ww  w .  j a v a  2  s.  c  o m
 */
@Override
protected void buildEvents(final DateTime start, final DateTime end) {
    final TemplateEntry activeTemplateEntry = filter.getActiveTemplateEntry();
    if (activeTemplateEntry == null) {
        // Nothing to build.
        return;
    }
    final Set<Integer> visibleCalendars = activeTemplateEntry.getVisibleCalendarIds();
    if (CollectionUtils.isEmpty(visibleCalendars) == true) {
        // Nothing to build.
        return;
    }
    final TeamEventFilter eventFilter = new TeamEventFilter();
    eventFilter.setTeamCals(visibleCalendars);
    eventFilter.setStartDate(start.toDate());
    eventFilter.setEndDate(end.toDate());
    eventFilter.setUser(ThreadLocalUserContext.getUser());
    final List<TeamEvent> teamEvents = teamEventDao.getEventList(eventFilter, true);

    boolean longFormat = false;
    days = Days.daysBetween(start, end).getDays();
    if (days < 10) {
        // Week or day view:
        longFormat = true;
    }

    final TeamCalRight right = new TeamCalRight(accessChecker);
    final PFUserDO user = ThreadLocalUserContext.getUser();
    final TimeZone timeZone = ThreadLocalUserContext.getTimeZone();
    if (CollectionUtils.isNotEmpty(teamEvents) == true) {
        for (final TeamEvent teamEvent : teamEvents) {
            final DateTime startDate = new DateTime(teamEvent.getStartDate(),
                    ThreadLocalUserContext.getDateTimeZone());
            final DateTime endDate = new DateTime(teamEvent.getEndDate(),
                    ThreadLocalUserContext.getDateTimeZone());
            final TeamEventDO eventDO;
            final TeamCalEventId id = new TeamCalEventId(teamEvent, timeZone);
            if (teamEvent instanceof TeamEventDO) {
                eventDO = (TeamEventDO) teamEvent;
            } else {
                eventDO = ((TeamRecurrenceEvent) teamEvent).getMaster();
            }
            teamEventMap.put(id.toString(), teamEvent);
            final MyWicketEvent event = new MyWicketEvent();
            event.setClassName(
                    EVENT_CLASS_NAME + " " + EventDroppedCallbackScriptGenerator.NO_CONTEXTMENU_INDICATOR);
            event.setId("" + id);
            event.setColor(activeTemplateEntry.getColorCode(eventDO.getCalendarId()));

            if (eventRight.hasUpdateAccess(ThreadLocalUserContext.getUser(), eventDO, null)) {
                event.setEditable(true);
            } else {
                event.setEditable(false);
            }

            // id <= 0 is hint for abo events -> not editable
            if (eventDO.getId() != null && eventDO.getId() <= 0) {
                event.setEditable(false);
            }

            if (teamEvent.isAllDay() == true) {
                event.setAllDay(true);
            }

            event.setStart(startDate);
            event.setEnd(endDate);

            String recurrence = null;
            if (eventDO.hasRecurrence() == true) {
                final Recur recur = eventDO.getRecurrenceObject();
                final TeamEventRecurrenceData recurrenceData = new TeamEventRecurrenceData(recur,
                        ThreadLocalUserContext.getTimeZone());
                final RecurrenceFrequency frequency = recurrenceData.getFrequency();
                if (frequency != null) {
                    final String unitI18nKey = frequency.getUnitI18nKey();
                    if (unitI18nKey != null) {
                        recurrence = recurrenceData.getInterval() + " " + getString(unitI18nKey);
                    }
                }
            }
            String reminder = null;
            if (eventDO.getReminderActionType() != null
                    && NumberHelper.greaterZero(eventDO.getReminderDuration()) == true
                    && eventDO.getReminderDurationUnit() != null) {
                reminder = getString(eventDO.getReminderActionType().getI18nKey()) + " "
                        + eventDO.getReminderDuration() + " "
                        + getString(eventDO.getReminderDurationUnit().getI18nKey());
            }
            event.setTooltip(eventDO.getCalendar().getTitle(),
                    new String[][] { { eventDO.getSubject() },
                            { eventDO.getLocation(), getString("timesheet.location") },
                            { eventDO.getNote(), getString("plugins.teamcal.event.note") },
                            { recurrence, getString("plugins.teamcal.event.recurrence") },
                            { reminder, getString("plugins.teamcal.event.reminder") } });
            final String title;
            String durationString = "";
            if (longFormat == true) {
                // String day = duration.getDays() + "";
                final Period period = new Period(startDate, endDate);
                int hourInt = period.getHours();
                if (period.getDays() > 0) {
                    hourInt += period.getDays() * 24;
                }
                final String hour = hourInt < 10 ? "0" + hourInt : "" + hourInt;

                final int minuteInt = period.getMinutes();
                final String minute = minuteInt < 10 ? "0" + minuteInt : "" + minuteInt;

                if (event.isAllDay() == false) {
                    durationString = "\n"
                            + ThreadLocalUserContext.getLocalizedString("plugins.teamcal.event.duration") + ": "
                            + hour + ":" + minute;
                }
                final StringBuffer buf = new StringBuffer();
                buf.append(teamEvent.getSubject());
                if (StringUtils.isNotBlank(teamEvent.getNote()) == true) {
                    buf.append("\n")
                            .append(ThreadLocalUserContext.getLocalizedString("plugins.teamcal.event.note"))
                            .append(": ").append(teamEvent.getNote());
                }
                buf.append(durationString);
                title = buf.toString();
            } else {
                title = teamEvent.getSubject();
            }
            if (right.hasMinimalAccess(eventDO.getCalendar(), user.getId()) == true) {
                // for minimal access
                event.setTitle("");
                event.setEditable(false);
            } else {
                event.setTitle(title);
            }
            events.put(id + "", event);
        }
    }
}

From source file:org.samcrow.ridgesurvey.data.ObservationItemView.java

License:Open Source License

/**
 * Formats a duration with a human-friendly form of [] minutes/hours... ago
 * @param duration the duration to format
 * @return a representation of the duration
 *///from   w  w w  .j a  va 2s.  co  m
private static String formatAgo(Period duration) {
    if (duration.getDays() > 1) {
        return String.format(Locale.getDefault(), "%d days ago", duration.getDays());
    }
    if (duration.getHours() > 1) {
        return String.format(Locale.getDefault(), "%d hours ago", duration.getHours());
    }
    if (duration.getMinutes() > 1) {
        return String.format(Locale.getDefault(), "%d minutes ago", duration.getMinutes());
    } else {
        return "Just now";
    }
}

From source file:org.wicketstuff.calendarviews.BaseCalendarView.java

License:Apache License

protected IDataProvider<DateMidnight> createDaysDataProvider(final DateTime start, final DateTime end,
        final Period period) {
    return new IDataProvider<DateMidnight>() {
        private static final long serialVersionUID = 1L;

        public Iterator<? extends DateMidnight> iterator(final long first, long count) {
            return createDateMidnightIterator(start, end, (int) first, (int) count);
        }/*from  w  w w.j a  v  a  2s .  co  m*/

        public IModel<DateMidnight> model(DateMidnight object) {
            return new Model<DateMidnight>(object);
        }

        public long size() {
            return period.getDays() + 1;
        }

        public void detach() {
            // no-op
        }

        @Override
        public String toString() {
            return "BaseCalendarView#DaysDataProvider [size: " + size() + "]";
        }
    };
}

From source file:org.wicketstuff.calendarviews.FullWeekCalendarView.java

License:Apache License

/**
 * This implementation makes sure to include the entire data range specified by the start date
 * and end date passed in to the constructor, and any additional days before and after that are
 * needed to complete the full weeks contained in this view.
 * /*  w ww  . j  a  v  a2 s .co m*/
 * @return a data provider of days to be shown on the calendar
 */
protected final IDataProvider<DateMidnight> createDaysDataProvider() {
    int firstDOW = getFirstDayOfWeek();
    int lastDOW = getLastDayOfWeek();
    // TODO: is this logic right? doing this since JODA has Sunday as day 7
    int add = firstDOW > lastDOW ? -7 : 0;
    final DateTime start = new DateTime(getStartDate()).withDayOfWeek(firstDOW).plusDays(add);
    final DateTime end = new DateTime(getEndDate()).withDayOfWeek(lastDOW);
    final Period period = new Period(start, end, PeriodType.days());

    getEventProvider().initializeWithDateRange(start.toDate(), end.toDate());

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("start: " + start + "; end: " + end + "; days: " + period.getDays());
    }

    return createDaysDataProvider(start, end, period);
}

From source file:org.wisdom.akka.impl.Job.java

License:Apache License

/**
 * Translates the given (Joda) Period to (Scala) duration.
 *
 * @param period the period/*w  w w  .  j a  va  2s  .com*/
 * @return the duration representing the same amount of time
 */
public static FiniteDuration toDuration(Period period) {
    return Duration.create(period.getDays(), TimeUnit.DAYS)
            .plus(Duration.create(period.getHours(), TimeUnit.HOURS)
                    .plus(Duration.create(period.getMinutes(), TimeUnit.MINUTES)
                            .plus(Duration.create(period.getSeconds(), TimeUnit.SECONDS))));
}

From source file:org.wso2.carbon.apimgt.usage.client.impl.APIUsageStatisticsRestClientImpl.java

License:Open Source License

/**
 * This method is used to get the breakdown of the duration between 2 days/timestamps in terms of years,
 * months, days, hours, minutes and seconds
 *
 * @param fromDate Start timestamp of the duration
 * @param toDate   End timestamp of the duration
 * @return A map containing the breakdown
 * @throws APIMgtUsageQueryServiceClientException when there is an error during date parsing
 *///from  www  .  j ava  2 s.  c  o m
private Map<String, Integer> getDurationBreakdown(String fromDate, String toDate)
        throws APIMgtUsageQueryServiceClientException {
    Map<String, Integer> durationBreakdown = new HashMap<String, Integer>();

    DateTimeFormatter formatter = DateTimeFormat
            .forPattern(APIUsageStatisticsClientConstants.TIMESTAMP_PATTERN);
    LocalDateTime startDate = LocalDateTime.parse(fromDate, formatter);
    LocalDateTime endDate = LocalDateTime.parse(toDate, formatter);
    Period period = new Period(startDate, endDate);
    int numOfYears = period.getYears();
    int numOfMonths = period.getMonths();
    int numOfWeeks = period.getWeeks();
    int numOfDays = period.getDays();
    if (numOfWeeks > 0) {
        numOfDays += numOfWeeks * 7;
    }
    int numOfHours = period.getHours();
    int numOfMinutes = period.getMinutes();
    int numOfSeconds = period.getSeconds();
    durationBreakdown.put(APIUsageStatisticsClientConstants.DURATION_YEARS, numOfYears);
    durationBreakdown.put(APIUsageStatisticsClientConstants.DURATION_MONTHS, numOfMonths);
    durationBreakdown.put(APIUsageStatisticsClientConstants.DURATION_DAYS, numOfDays);
    durationBreakdown.put(APIUsageStatisticsClientConstants.DURATION_WEEKS, numOfWeeks);
    durationBreakdown.put(APIUsageStatisticsClientConstants.DURATION_HOURS, numOfHours);
    durationBreakdown.put(APIUsageStatisticsClientConstants.DURATION_MINUTES, numOfMinutes);
    durationBreakdown.put(APIUsageStatisticsClientConstants.DURATION_SECONDS, numOfSeconds);
    return durationBreakdown;
}

From source file:pt.ist.fenix.task.exportData.santanderCardGeneration.CreateAndInitializeExecutionCourses.java

License:Open Source License

private int findOffset(final Lesson oldLesson) {
    final GenericPair<YearMonthDay, YearMonthDay> maxLessonsPeriod = oldLesson.getExecutionCourse()
            .getMaxLessonsPeriod();//from w w w  . j  a  va2  s. c  om
    final LessonInstance lessonInstance = oldLesson.getFirstLessonInstance();
    final Period period;
    if (lessonInstance != null) {
        period = new Period(maxLessonsPeriod.getLeft(), lessonInstance.getDay());
    } else if (oldLesson.getPeriod() != null) {
        final YearMonthDay start = oldLesson.getPeriod().getStartYearMonthDay();
        period = new Period(maxLessonsPeriod.getLeft(), start);
    } else {
        period = null;
    }
    return period == null ? 0 : period.getMonths() * 4 + period.getWeeks() + (period.getDays() / 7);
}

From source file:se.toxbee.sleepfighter.text.DateTextUtils.java

License:Open Source License

/**
 * Builds and returns earliest text when given a resources bundle.
 *
 * @param formats an array of strings containing formats for [no-alarm-active, < minute, xx-yy-zz, xx-yy, xx]
 *       where xx, yy, zz can be either day, hours, minutes (non-respectively).
 * @param partsFormat an array of strings containing part formats for [day, month, hour].
 * @param diff difference between now and ats.
 * @param ats an AlarmTimestamp: the information about the alarm & its timestamp.
 * @return the built time-to string./* w  ww .  j  a v  a 2 s .  co m*/
 */
public static final String getTimeToText(String[] formats, String[] partFormats, Period diff,
        AlarmTimestamp ats) {
    String earliestText;

    // Not real? = we don't have any alarms active.
    if (ats == AlarmTimestamp.INVALID) {
        earliestText = formats[0];
    } else {
        int[] diffVal = { Math.abs(diff.getDays()), Math.abs(diff.getHours()), Math.abs(diff.getMinutes()) };

        // What fields are set?
        BitSet setFields = new BitSet(3);
        setFields.set(0, diffVal[0] != 0);
        setFields.set(1, diffVal[1] != 0);
        setFields.set(2, diffVal[2] != 0);
        int cardinality = setFields.cardinality();

        earliestText = formats[cardinality + 1];

        if (cardinality > 0) {
            List<String> args = new ArrayList<String>(3);

            for (int i = setFields.nextSetBit(0); i >= 0; i = setFields.nextSetBit(i + 1)) {
                args.add(partFormats[i]);
            }

            // Finally format everything.
            earliestText = String.format(earliestText, args.toArray());

            earliestText = String.format(earliestText, diffVal[0], diffVal[1], diffVal[2]);
        } else {
            // only seconds remains until it goes off.
            earliestText = formats[1];
        }
    }

    return earliestText;
}