Example usage for org.joda.time DateMidnight toDateTime

List of usage examples for org.joda.time DateMidnight toDateTime

Introduction

In this page you can find the example usage for org.joda.time DateMidnight toDateTime.

Prototype

DateTime toDateTime();

Source Link

Document

Get this object as a DateTime.

Usage

From source file:org.filteredpush.qc.date.DateUtils.java

License:Apache License

/**
 * Given a string that may be a date or a date range, extract a interval of
 * dates from that date range, up to the end milisecond of the last day.
 * //from   w  w w . j av  a 2 s  . c  o  m
 * @see DateUtils#extractDateInterval(String) which returns a pair of DateMidnights.
 * 
 * @param eventDate a string containing a dwc:eventDate from which to extract an interval.
 * @return an interval from the beginning of event date to the end of event date.
 */
public static Interval extractInterval(String eventDate) {
    Interval result = null;
    DateTimeParser[] parsers = { DateTimeFormat.forPattern("yyyy-MM").getParser(),
            DateTimeFormat.forPattern("yyyy").getParser(),
            ISODateTimeFormat.dateOptionalTimeParser().getParser() };
    DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter();
    if (eventDate != null && eventDate.contains("/") && isRange(eventDate)) {
        String[] dateBits = eventDate.split("/");
        try {
            // must be at least a 4 digit year.
            if (dateBits[0].length() > 3 && dateBits[1].length() > 3) {
                DateMidnight startDate = DateMidnight.parse(dateBits[0], formatter);
                DateTime endDate = DateTime.parse(dateBits[1], formatter);
                logger.debug(startDate);
                logger.debug(endDate);
                if (dateBits[1].length() == 4) {
                    result = new Interval(startDate, endDate.plusMonths(12).minus(1l));
                } else if (dateBits[1].length() == 7) {
                    result = new Interval(startDate, endDate.plusMonths(1).minus(1l));
                } else {
                    result = new Interval(startDate, endDate.plusDays(1).minus(1l));
                }
                logger.debug(result);
            }
        } catch (Exception e) {
            // not a date range
            logger.error(e.getMessage());
        }
    } else {
        try {
            DateMidnight startDate = DateMidnight.parse(eventDate, formatter);
            logger.debug(startDate);
            if (eventDate.length() == 4) {
                DateTime endDate = startDate.toDateTime().plusMonths(12).minus(1l);
                result = new Interval(startDate, endDate);
                logger.debug(result);
            } else if (eventDate.length() == 7) {
                DateTime endDate = startDate.toDateTime().plusMonths(1).minus(1l);
                result = new Interval(startDate, endDate);
                logger.debug(result);
            } else {
                DateTime endDate = startDate.toDateTime().plusDays(1).minus(1l);
                result = new Interval(startDate, endDate);
                logger.debug(result);
            }
        } catch (Exception e) {
            // not a date
            logger.error(e.getMessage());
        }
    }
    return result;
}

From source file:org.jasig.portal.portlets.statistics.BaseStatisticsReportController.java

License:Apache License

/**
 * Build the aggregation {@link DataTable}
 */// w w w  .j a  v  a2  s .com
protected final DataTable buildAggregationReport(F form) throws TypeMismatchException {
    //Pull data out of form for per-group fetching
    final AggregationInterval interval = form.getInterval();
    final DateMidnight start = form.getStart();
    final DateMidnight end = form.getEnd();

    final DateTime startDateTime = start.toDateTime();
    //Use a query end of the end date at 23:59:59
    final DateTime endDateTime = end.plusDays(1).toDateTime().minusSeconds(1);

    //Get the list of DateTimes used on the X axis in the report
    final List<DateTime> reportTimes = this.intervalHelper.getIntervalStartDateTimesBetween(interval,
            startDateTime, endDateTime, maxIntervals);

    final Map<D, SortedSet<T>> groupedAggregations = createColumnDiscriminatorMap(form);

    //Determine the ValueType of the date/time column. Use the most specific column type possible
    final ValueType dateTimeColumnType;
    if (interval.isHasTimePart()) {
        //If start/end are the same day just display the time
        if (startDateTime.toDateMidnight().equals(endDateTime.toDateMidnight())) {
            dateTimeColumnType = ValueType.TIMEOFDAY;
        }
        //interval has time data and start/end are on different days, show full date time
        else {
            dateTimeColumnType = ValueType.DATETIME;
        }
    }
    //interval is date only
    else {
        dateTimeColumnType = ValueType.DATE;
    }

    //Setup the date/time column description
    final ColumnDescription dateTimeColumn;
    switch (dateTimeColumnType) {
    case TIMEOFDAY: {
        dateTimeColumn = new ColumnDescription("time", dateTimeColumnType, "Time");
        break;
    }
    default: {
        dateTimeColumn = new ColumnDescription("date", dateTimeColumnType, "Date");
    }
    }

    final DataTable table = new JsonDataTable();
    table.addColumn(dateTimeColumn);

    //Setup columns in the DataTable 
    final Set<D> columnGroups = groupedAggregations.keySet();
    for (final D columnMapping : columnGroups) {
        final Collection<ColumnDescription> columnDescriptions = this.getColumnDescriptions(columnMapping,
                form);
        table.addColumns(columnDescriptions);
    }

    //Query for all aggregation data in the time range for all groups.  Only the
    //interval and discriminator data is used from the keys.
    final Set<K> keys = createAggregationsQueryKeyset(columnGroups, form);
    final BaseAggregationDao<T, K> baseAggregationDao = this.getBaseAggregationDao();
    final Collection<T> aggregations = baseAggregationDao.getAggregations(startDateTime, endDateTime, keys,
            extractGroupsArray(columnGroups));

    //Organize the results by group and sort them chronologically by adding them to the sorted set
    for (final T aggregation : aggregations) {
        final D discriminator = aggregation.getAggregationDiscriminator();
        final SortedSet<T> results = groupedAggregations.get(discriminator);
        results.add(aggregation);
    }

    //Build Map from discriminator column mapping to result iterator to allow putting results into
    //the correct column AND the correct time slot in the column
    Comparator<? super D> comparator = getDiscriminatorComparator();
    final Map<D, PeekingIterator<T>> groupedAggregationIterators = new TreeMap<D, PeekingIterator<T>>(
            (comparator));
    for (final Entry<D, SortedSet<T>> groupedAggregationEntry : groupedAggregations.entrySet()) {
        groupedAggregationIterators.put(groupedAggregationEntry.getKey(),
                Iterators.peekingIterator(groupedAggregationEntry.getValue().iterator()));
    }

    /*
     * populate the data, filling in blank spots. The full list of interval DateTimes is used to create every row in the
     * query range. Then the iterator
     */
    for (final DateTime rowTime : reportTimes) {
        // create the row
        final TableRow row = new TableRow();

        // add the date to the first cell
        final Value dateTimeValue;
        switch (dateTimeColumnType) {
        case DATE: {
            dateTimeValue = new DateValue(rowTime.getYear(), rowTime.getMonthOfYear() - 1,
                    rowTime.getDayOfMonth());
            break;
        }
        case TIMEOFDAY: {
            dateTimeValue = new TimeOfDayValue(rowTime.getHourOfDay(), rowTime.getMinuteOfHour(), 0);
            break;
        }
        default: {
            dateTimeValue = new DateTimeValue(rowTime.getYear(), rowTime.getMonthOfYear() - 1,
                    rowTime.getDayOfMonth(), rowTime.getHourOfDay(), rowTime.getMinuteOfHour(), 0, 0);
            break;
        }
        }
        row.addCell(new TableCell(dateTimeValue));

        for (final PeekingIterator<T> groupedAggregationIteratorEntry : groupedAggregationIterators.values()) {
            List<Value> values = null;

            if (groupedAggregationIteratorEntry.hasNext()) {
                final T aggr = groupedAggregationIteratorEntry.peek();
                if (rowTime.equals(aggr.getDateTime())) {
                    //Data is for the correct time slot, advance the iterator
                    groupedAggregationIteratorEntry.next();

                    values = createRowValues(aggr, form);
                }
            }

            //Gap in the data, fill it in using a null aggregation
            if (values == null) {
                values = createRowValues(null, form);
            }

            //Add the values to the row
            for (final Value value : values) {
                row.addCell(value);
            }
        }

        table.addRow(row);
    }

    return table;
}

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

License:Open Source License

/**
 * @see org.projectforge.web.calendar.MyFullCalendarEventsProvider#buildEvents(org.joda.time.DateTime, org.joda.time.DateTime)
 *///from ww  w  .  j ava  2 s  .co  m
@Override
protected void buildEvents(final DateTime start, final DateTime end) {
    DateMidnight day = new DateMidnight(start);
    int idCounter = 0;
    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 DayHolder dh = new DayHolder(day.toDate());
        String backgroundColor, color, textColor;
        if (dh.isHoliday() == true) {
            if (dh.isWorkingDay() == true) {
                backgroundColor = "#FFF0F0";
                color = "#EEEEEE";
                textColor = "#222222";
            } else {
                backgroundColor = "#f9dfde";
                color = "#EEEEEE";
                textColor = "#FF2222";
            }
        } else {
            day = day.plusDays(1);
            continue;
        }

        final Event event = new Event().setAllDay(true);
        final String id = "h-" + (++idCounter);
        event.setId(id);
        event.setStart(day.toDateTime());
        String title;
        final String holidayInfo = dh.getHolidayInfo();
        if (holidayInfo != null && holidayInfo.startsWith("calendar.holiday.") == true) {
            title = getString(holidayInfo);
        } else {
            title = holidayInfo;
        }
        event.setTitle(title);
        event.setBackgroundColor(backgroundColor);
        event.setColor(color);
        event.setTextColor(textColor);
        events.put(id, event);
        day = day.plusDays(1);
    } while (day.isAfter(end) == false);
}