Example usage for org.joda.time DateTime getYear

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

Introduction

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

Prototype

public int getYear() 

Source Link

Document

Get the year field value.

Usage

From source file:org.apache.tajo.util.datetime.DateTimeUtil.java

License:Apache License

public static long getYear(DateTime dateTime) {
    return convertToMicroSeconds(dateTime.withTimeAtStartOfDay().withDate(dateTime.getYear(), 1, 1));
}

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

License:Apache License

/** Build the aggregation {@link DataTable} */
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;
        }/*from w w  w  . j  a  v  a  2s  .co m*/
        //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.ash.history.CalendarH.java

License:Open Source License

/**
 * Gets the end value of time selection 
 * //ww w .  ja  va 2  s .  c  o m
 * @return the value
 */
long getEndSelectionPlus2659() {

    DateTime endDaySelect = new DateTime(getEndSelection());
    DateTime endDaySelectPlus2659 = new DateTime(endDaySelect.getYear(), endDaySelect.getMonthOfYear(),
            endDaySelect.getDayOfMonth(), 23, 59, 59, 999);

    if (endDaySelectPlus2659.getMillis() < getEndBDB()) {
        return endDaySelectPlus2659.getMillis();
    } else {
        return getEndBDB();
    }
}

From source file:org.ash.history.CalendarH.java

License:Open Source License

/**
 * Get fragged days for Calendar.//w  ww. j ava2s . c  o m
 * 
 * @param begin0
 * @param end0
 * @return
 */
private long[] getFraggedDays(long begin0, long end0) {

    DateTime begin = new DateTime(begin0);
    DateTime end = new DateTime(end0);

    DateTime beginTmp = new DateTime(begin);
    DateTime beginDayPlus0000 = new DateTime(beginTmp.getYear(), beginTmp.getMonthOfYear(),
            beginTmp.getDayOfMonth(), 0, 0, 0, 0);
    DateTime endTmp = new DateTime(end);
    DateTime endPlus2359 = new DateTime(endTmp.getYear(), endTmp.getMonthOfYear(), endTmp.getDayOfMonth(), 23,
            59, 59, 999);

    Interval interval = new Interval(beginDayPlus0000, endPlus2359);
    Days days = Days.daysIn(interval);

    int daysBetween = days.getDays();

    long[] flaggedDates = new long[daysBetween + 1];

    DateTime tmp = new DateTime(begin);
    // Load days.
    for (int i = 0; i <= daysBetween; i++) {
        DateTime tmp1 = tmp.plusDays(i);
        flaggedDates[i] = tmp1.getMillis();
    }

    return flaggedDates;
}

From source file:org.assertj.jodatime.api.DateTimeAssert.java

License:Apache License

/**
 * Returns true if both datetime are in the same year, false otherwise.
 * /*from   ww w . jav a 2s  . c  o  m*/
 * @param actual the actual datetime. expected not be null
 * @param other the other datetime. expected not be null
 * @return true if both datetime are in the same year, false otherwise
 */
private static boolean haveSameYear(DateTime actual, DateTime other) {
    return actual.getYear() == other.getYear();
}

From source file:org.attribyte.wp.model.Site.java

License:Apache License

/**
 * Builds the permalink for a post from this site.
 * @param post The post./*from   w ww  .j  a  v a 2s .c  om*/
 * @return The permalink string.
 * @see <a href="https://codex.wordpress.org/Using_Permalinks">https://codex.wordpress.org/Using_Permalinks</a>
 */
public String buildPermalink(final Post post) {

    final String authorSlug = post.author != null ? Strings.nullToEmpty(post.author.slug) : "";
    final List<TaxonomyTerm> categories = post.categories();
    final Term categoryTerm = categories.size() > 0 ? categories.get(0).term : defaultCategory;
    final String category = categoryTerm != null ? categoryTerm.slug : "";
    final String post_id = Long.toString(post.id);
    final DateTime publishTime = new DateTime(post.publishTimestamp);
    final String year = Integer.toString(publishTime.getYear());
    final String monthnum = String.format("%02d", publishTime.getMonthOfYear());
    final String day = String.format("%02d", publishTime.getDayOfMonth());
    final String hour = String.format("%02d", publishTime.getHourOfDay());
    final String minute = String.format("%02d", publishTime.getMinuteOfHour());
    final String second = String.format("%02d", publishTime.getSecondOfMinute());
    final String path = permalinkStructure.replace("%year%", year).replace("%monthnum%", monthnum)
            .replace("%day%", day).replace("%hour%", hour).replace("%minute%", minute)
            .replace("%second%", second).replace("%post_id%", post_id).replace("%postname%", post.slug)
            .replace("%category%", category).replace("%author%", authorSlug);
    return baseURL + path;
}

From source file:org.conqat.engine.bugzilla.lib.Bug.java

License:Apache License

/** Get milliseconds of an enumeration field that is holding a date. */
public long getMilliSeconds(EBugzillaField field) {
    // TODO (BH): Why variable here?
    long milliSeconds = 0;

    // TODO (BH): I would invert the condition and return/throw here to
    // reduce the nesting.
    if (fields.get(field) != null) {

        // TODO (BH): Why store value and overwrite in next line? You could
        // also move this outside of the if and use the variable in the if
        // expression.
        String bugzillaDate = StringUtils.EMPTY_STRING;
        bugzillaDate = fields.get(field);

        // TODO (BH): Make constants from these pattern
        Pattern todayPattern = Pattern.compile("[0-9]{2}:[0-9]{2}:[0-9]{2}");
        Pattern lastWeekPattern = Pattern.compile("[A-Z][a-z][a-z] [0-9]{2}:[0-9]{2}");
        Pattern anyDatePattern = Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2}");

        // TODO (BH): Variables only used once. Inline?
        Matcher todayMatcher = todayPattern.matcher(bugzillaDate);
        Matcher lastWeekMatcher = lastWeekPattern.matcher(bugzillaDate);
        Matcher anyDateMatcher = anyDatePattern.matcher(bugzillaDate);

        if (anyDateMatcher.matches()) {

            // TODO (BH): Make this a constant?
            DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd");
            // TODO (BH): Directly return?
            milliSeconds = dateTimeFormatter.parseDateTime(bugzillaDate).getMillis();

        } else if (lastWeekMatcher.matches()) {

            DateTime lastWeekDate = new DateTime(Chronic.parse(bugzillaDate).getBeginCalendar().getTime());

            // Since jchronic parses the Bugzilla format exactly seven days
            // to late, we need to subtract those 7 days.
            // TODO (BH): Directly return?
            milliSeconds = lastWeekDate.minusDays(7).getMillis();

        } else if (todayMatcher.matches()) {

            DateTime todayDate = new DateTime();

            // TODO (BH): Make this a constant?
            DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("HH:mm:ss");
            DateTime fieldDate = dateTimeFormatter.parseDateTime(bugzillaDate);

            // TODO (BH): Directly return?
            milliSeconds = new DateTime(todayDate.getYear(), todayDate.getMonthOfYear(),
                    todayDate.getDayOfMonth(), fieldDate.getHourOfDay(), fieldDate.getMinuteOfHour(),
                    fieldDate.getSecondOfMinute()).getMillis();

        } else {/*  w w  w  .  j  av a 2  s .  c o  m*/
            // TODO (BH): I think this is not a good way of handling this
            // error as the argument might be valid, but the data is just
            // not good. Better use a checked exception, such as
            // ConQATException.
            throw new IllegalArgumentException("Field is not a Bugzilla date.");
        }

    } else {
        // TODO (BH): I think this is not a good way of handling this error
        // as the argument might be valid, but the data is just not present.
        // Better use a checked exception, such as ConQATException.
        throw new IllegalArgumentException("Argument is not a Bugzilla field.");
    }

    return milliSeconds;
}

From source file:org.countandra.utils.CountandraUtils.java

License:Apache License

private void denormalizedIncrement(Mutator<String> m, String category, String ptimeDimensions,
        String denormalizedKey, long time, int value) {

    DateTime dt = new DateTime(time);
    DateTime dtm = new DateTime(dt.getYear(), dt.getMonthOfYear(), dt.getDayOfMonth(), dt.getHourOfDay(),
            dt.getMinuteOfHour());//  w  ww .j  ava  2 s.c o m
    DateTime dtH = new DateTime(dt.getYear(), dt.getMonthOfYear(), dt.getDayOfMonth(), dt.getHourOfDay(), 0);
    DateTime dtD = new DateTime(dt.getYear(), dt.getMonthOfYear(), dt.getDayOfMonth(), 0, 0);
    DateTime dtM = new DateTime(dt.getYear(), dt.getMonthOfYear(), 1, 0, 0);
    DateTime dtY = new DateTime(dt.getYear(), 1, 1, 0, 0);
    String[] timeDimensions = ptimeDimensions.split(",");

    for (int i = 0; i < timeDimensions.length; i++) {
        switch (hshSupportedTimeDimensions.get(timeDimensions[i])) {
        case MINUTELY:
            incrementCounter(m, category, denormalizedKey, TimeDimension.MINUTELY.getSCode(), dtm.getMillis(),
                    value);
            break;
        case HOURLY:
            incrementCounter(m, category, denormalizedKey, TimeDimension.HOURLY.getSCode(), dtH.getMillis(),
                    value);
            break;
        case DAILY:
            incrementCounter(m, category, denormalizedKey, TimeDimension.DAILY.getSCode(), dtD.getMillis(),
                    value);
            break;
        case MONTHLY:
            incrementCounter(m, category, denormalizedKey, TimeDimension.MONTHLY.getSCode(), dtM.getMillis(),
                    value);
            break;
        case YEARLY:
            incrementCounter(m, category, denormalizedKey, TimeDimension.YEARLY.getSCode(), dtY.getMillis(),
                    value);
            break;
        case ALLTIME:
            incrementCounter(m, category, denormalizedKey, TimeDimension.ALLTIME.getSCode(), 0L, value);
            break;

        }
    }
}

From source file:org.dataconservancy.packaging.gui.presenter.impl.PackageMetadataPresenterImpl.java

License:Apache License

private void setExistingValues() {
    if (getController().getPackageState().hasPackageMetadataValues()) {
        view.clearAllFields();/*from ww w  . jav  a  2  s . c  o  m*/

        if (!Util.isEmptyOrNull(getController().getPackageState().getPackageName())) {
            view.getPackageNameField().getPropertyInput()
                    .setText(getController().getPackageState().getPackageName());
        }

        if (getController().getPackageState()
                .getPackageMetadataValues(GeneralParameterNames.DOMAIN_PROFILE) != null
                && !getController().getPackageState()
                        .getPackageMetadataValues(GeneralParameterNames.DOMAIN_PROFILE).isEmpty()
                && !Util.isEmptyOrNull(getController().getPackageState()
                        .getPackageMetadataValues(GeneralParameterNames.DOMAIN_PROFILE).get(0))) {
            URI domainProfileURI = null;
            try {
                domainProfileURI = new URI(getController().getPackageState()
                        .getPackageMetadataValues(GeneralParameterNames.DOMAIN_PROFILE).get(0));
            } catch (URISyntaxException e) {
                view.getErrorLabel().setText(TextFactory.getText(ErrorKey.DOMAIN_PROFILE_PARSE_ERROR));
                view.getErrorLabel().setVisible(true);
                view.scrollToTop();
            }

            if (domainProfileURI != null) {
                for (Map.Entry<String, URI> idEntry : domainProfileIdMap.entrySet()) {
                    if (idEntry.getValue().equals(domainProfileURI)) {
                        view.getDomainProfilesComboBox().setValue(idEntry.getKey());
                        break;
                    }
                }
            }
        }

        view.getAllDynamicFields().stream().filter(
                node -> getController().getPackageState().getPackageMetadataValues(node.getId()) != null)
                .forEach(node -> {
                    if (node instanceof TextPropertyBox) {
                        if (node.getUserData() == null
                                || !((String) node.getUserData()).equalsIgnoreCase("repeatable")) {
                            ((TextPropertyBox) node).getPropertyInput().setText(getController()
                                    .getPackageState().getPackageMetadataValues(node.getId()).get(0));
                        }
                    } else if (node instanceof DatePropertyBox) {
                        DateTime date = DateUtility.parseDateString(getController().getPackageState()
                                .getPackageMetadataValues(node.getId()).get(0));
                        if (date != null) {
                            ((DatePropertyBox) node).getPropertyInput().setValue(
                                    LocalDate.of(date.getYear(), date.getMonthOfYear(), date.getDayOfMonth()));
                        }
                    } else if (node instanceof VBox) {
                        getController().getPackageState().getPackageMetadataValues(node.getId()).stream()
                                .filter(value -> !Util.isEmptyOrNull(value)).forEach(value -> ((VBox) node)
                                        .getChildren().add(new RemovableLabel(value, (VBox) node)));
                    }
                });
    }
}

From source file:org.dataconservancy.ui.services.CollectionActivityServiceImpl.java

License:Apache License

/**
 * returns creation activity for a collection
 * @param collection/*w w w  .j  a  v a2 s .co  m*/
 * @return activity
 */
private Activity retrieveCreationActivityForCollection(Collection collection) {
    DateTime depositDate = collection.getDepositDate();

    Activity activity = new Activity();
    Person actor = userService.get(collection.getDepositorId());
    activity.setActor(actor);
    activity.setDateTimeOfOccurrence(new DateTime(depositDate.getYear(), depositDate.getMonthOfYear(),
            depositDate.getDayOfMonth(), depositDate.getHourOfDay(), depositDate.getMinuteOfHour(),
            depositDate.getSecondOfMinute()));
    activity.setType(Activity.Type.COLLECTION_DEPOSIT);
    activity.setCount(1);

    return activity;
}