Example usage for org.joda.time DateTime plusMinutes

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

Introduction

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

Prototype

public DateTime plusMinutes(int minutes) 

Source Link

Document

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

Usage

From source file:dk.teachus.frontend.pages.periods.PeriodPage.java

License:Apache License

public PeriodPage(final Period period) {
    super(UserLevel.TEACHER, true);

    add(new Label("editPeriodTitle", TeachUsSession.get().getString("PeriodPage.editForm"))); //$NON-NLS-1$ //$NON-NLS-2$

    final FormPanel form = new FormPanel("form"); //$NON-NLS-1$
    add(form);/*from   w  w  w .  j  a  v  a  2 s.  co  m*/

    // Name
    final StringTextFieldElement nameElement = new StringTextFieldElement(
            TeachUsSession.get().getString("General.name"), new PropertyModel<String>(period, "name"), true); //$NON-NLS-1$ //$NON-NLS-2$
    nameElement.add(StringValidator.maximumLength(100));
    nameElement.setReadOnly(period.getStatus() != Status.DRAFT);
    form.addElement(nameElement);

    // Begin date
    final DateElement beginDateElement = new DateElement(TeachUsSession.get().getString("General.startDate"), //$NON-NLS-1$
            new PropertyModel<DateMidnight>(period, "beginDate")); //$NON-NLS-1$
    beginDateElement.setReadOnly(period.getStatus() != Status.DRAFT);
    form.addElement(beginDateElement);

    // End date
    final DateElement endDateElement = new DateElement(TeachUsSession.get().getString("General.endDate"), //$NON-NLS-1$
            new PropertyModel<DateMidnight>(period, "endDate")); //$NON-NLS-1$
    endDateElement.add(new IValidator<DateMidnight>() {
        private static final long serialVersionUID = 1L;

        public void validate(IValidatable<DateMidnight> validatable) {
            DateMidnight date = validatable.getValue();
            if (date != null) {
                // Check if the end date conflicts with some bookings
                if (period.getId() != null) {
                    BookingDAO bookingDAO = TeachUsApplication.get().getBookingDAO();
                    DateTime lastBookingDate = bookingDAO.getLastBookingDate(period);
                    if (lastBookingDate != null) {
                        if (date.isBefore(lastBookingDate)) {
                            ValidationError validationError = new ValidationError();
                            String bookingConflictMessage = TeachUsSession.get()
                                    .getString("PeriodPage.endDateBookingConflict");
                            bookingConflictMessage = bookingConflictMessage.replace("${lastBookingDate}",
                                    Formatters.getFormatPrettyDate().print(lastBookingDate));
                            validationError.setMessage(bookingConflictMessage); //$NON-NLS-1$
                            validatable.error(validationError);
                        }
                    }
                }
            }
        }
    });
    form.addElement(endDateElement);

    // Time elements
    final List<Integer> hours = new ArrayList<Integer>();
    DateTime dt = new DateTime().withTime(0, 0, 0, 0);
    final int day = dt.getDayOfMonth();
    while (day == dt.getDayOfMonth()) {
        hours.add(dt.getMinuteOfDay());
        dt = dt.plusMinutes(30);
    }

    final TimeChoiceRenderer<Integer> timeChoiceRenderer = new TimeChoiceRenderer<Integer>();

    // Start time
    final DropDownElement<Integer> startTimeElement = new DropDownElement<Integer>(
            TeachUsSession.get().getString("General.startTime"), new TimeModel(new PropertyModel<LocalTime>( //$NON-NLS-1$
                    period, "startTime")), //$NON-NLS-1$
            hours, timeChoiceRenderer, true);
    startTimeElement.setReadOnly(period.getStatus() != Status.DRAFT);
    form.addElement(startTimeElement);

    // End time
    final DropDownElement<Integer> endTimeElement = new DropDownElement<Integer>(
            TeachUsSession.get().getString("General.endTime"), //$NON-NLS-1$
            new TimeModel(new PropertyModel<LocalTime>(period, "endTime")),
            hours, timeChoiceRenderer, true);
    endTimeElement.setReadOnly(period.getStatus() != Status.DRAFT);
    form.addElement(endTimeElement);

    // Location
    final StringTextFieldElement locationElement = new StringTextFieldElement(
            TeachUsSession.get().getString("General.location"), new PropertyModel<String>(period, "location")); //$NON-NLS-1$ //$NON-NLS-2$
    locationElement.add(StringValidator.maximumLength(100));
    locationElement.setReadOnly(period.getStatus() != Status.DRAFT);
    form.addElement(locationElement);

    // Price
    final DecimalFieldElement priceElement = new DecimalFieldElement(
            TeachUsSession.get().getString("General.price"), new PropertyModel<Double>(period, "price"), 6); //$NON-NLS-1$ //$NON-NLS-2$
    priceElement.setReadOnly(period.getStatus() != Status.DRAFT);
    priceElement.setDefaultNullValue(0.0);
    form.addElement(priceElement);

    // Lesson duration
    final IntegerFieldElement lessonDurationElement = new IntegerFieldElement(
            TeachUsSession.get().getString("General.lessonDuration"), new PropertyModel<Integer>( //$NON-NLS-1$
                    period, "lessonDuration"), //$NON-NLS-1$
            true, 4);
    lessonDurationElement.setReadOnly(period.getStatus() != Status.DRAFT);
    form.addElement(lessonDurationElement);

    // Interval Between Lesson Start
    final IntegerFieldElement intervalBetweenLessonStartElement = new IntegerFieldElement(
            TeachUsSession.get().getString("General.intervalBetweenLessonStart"), //$NON-NLS-1$
            new PropertyModel<Integer>(period, "intervalBetweenLessonStart"), true, 4); //$NON-NLS-1$
    intervalBetweenLessonStartElement.setReadOnly(period.getStatus() != Status.DRAFT);
    form.addElement(intervalBetweenLessonStartElement);

    // Week days
    final CheckGroupElement<WeekDay> weekDaysElement = new CheckGroupElement<WeekDay>(
            TeachUsSession.get().getString("General.weekDays"), new PropertyModel<List<WeekDay>>(period, //$NON-NLS-1$
                    "weekDays"), //$NON-NLS-1$
            Arrays.asList(WeekDay.values()), new WeekDayChoiceRenderer(Format.LONG), true);
    weekDaysElement.setReadOnly(period.getStatus() != Status.DRAFT);
    form.addElement(weekDaysElement);

    // Repeat every week
    final IntegerFieldElement repeatEveryWeekElement = new IntegerFieldElement(
            TeachUsSession.get().getString("General.repeatEveryWeek"), //$NON-NLS-1$
            new PropertyModel<Integer>(period, "repeatEveryWeek")); //$NON-NLS-1$
    repeatEveryWeekElement.setReadOnly(period.getStatus() != Status.DRAFT);
    //      repeatEveryWeekElement.setDefaultNullValue(1);
    form.addElement(repeatEveryWeekElement);

    // Status
    final List<Status> statusList = Arrays.asList(Status.values());
    final DropDownElement<Status> statusElement = new DropDownElement<Status>(
            TeachUsSession.get().getString("General.status"), new PropertyModel<Status>(period, "status"), //$NON-NLS-1$//$NON-NLS-2$
            statusList, new PeriodStatusRenderer());
    statusElement.setReadOnly(period.getStatus() != Status.DRAFT);
    form.addElement(statusElement);

    // Buttons
    form.addElement(new ButtonPanelElement() {
        private static final long serialVersionUID = 1L;

        @Override
        protected List<IButton> getAdditionalButtons() {
            final List<IButton> buttons = new ArrayList<IButton>();
            buttons.add(new IButton() {
                private static final long serialVersionUID = 1L;

                public String getValue() {
                    return TeachUsSession.get().getString("General.preview"); //$NON-NLS-1$
                }

                public void onClick(final AjaxRequestTarget target) {
                    final WebMarkupContainer preview = generatePreview(period);
                    PeriodPage.this.replace(preview);
                    target.add(preview);
                }
            });
            return buttons;
        }

        @Override
        protected void onCancel() {
            getRequestCycle().setResponsePage(PeriodsPage.class);
        }

        @Override
        protected void onSave(final AjaxRequestTarget target) {
            final PeriodDAO periodDAO = TeachUsApplication.get().getPeriodDAO();

            periodDAO.save(period);

            getRequestCycle().setResponsePage(PeriodsPage.class);
        }
    });

    add(new Label("previewTitle", TeachUsSession.get().getString("General.preview"))); //$NON-NLS-1$ //$NON-NLS-2$

    if (period.getId() != null) {
        add(generatePreview(period));
    } else {
        add(new WebComponent("calendar").setOutputMarkupId(true).setOutputMarkupPlaceholderTag(true)
                .setVisible(false));
    }
}

From source file:es.usc.citius.servando.calendula.scheduling.AlarmScheduler.java

License:Open Source License

public static boolean canBeScheduled(DateTime t, Context cxt) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(cxt);
    String delayMinutesStr = prefs.getString("alarm_reminder_window", "60");
    int window = (int) Long.parseLong(delayMinutesStr);
    return t.plusMinutes(window).isAfterNow();
}

From source file:eu.cassandra.training.consumption.ConsumptionEventRepo.java

License:Apache License

/**
 * /*  w w w.j  a va 2  s  .  c o  m*/
 * Function for importing consumption events from an file.
 * 
 * @param filename
 *          The name of the file that will be exported.
 * @throws FileNotFoundException
 */
public void readEventsFile(String filename, Installation installation) throws FileNotFoundException {

    int startMinute = 0;
    int endMinute = 0;
    int counter = 0;
    DateTime startDateTime = new DateTime();
    DateTime endDateTime = new DateTime();
    DateTime startDate = new DateTime();
    DateTime endDate = new DateTime();
    DateTime date = installation.getStartDate();

    System.out.println(filename);

    File file = new File(filename);

    Scanner scanner = new Scanner(file);

    String line = scanner.nextLine();
    String[] temp = new String[2];

    while (scanner.hasNext()) {

        line = scanner.nextLine();
        temp = line.split("-");

        startMinute = Integer.parseInt(temp[0]);
        endMinute = Integer.parseInt(temp[1]);

        startDateTime = date.plusMinutes(startMinute);
        endDateTime = date.plusMinutes(endMinute);

        startDate = new DateTime(startDateTime.getYear(), startDateTime.getMonthOfYear(),
                startDateTime.getDayOfMonth(), 0, 0);
        endDate = new DateTime(endDateTime.getYear(), endDateTime.getMonthOfYear(), endDateTime.getDayOfMonth(),
                0, 0);

        if (startDateTime.isAfter(endDateTime) == false)
            events.add(new ConsumptionEvent(counter++, startDateTime, startDate, endDateTime, endDate));
        else
            System.out.println("Start: " + startDateTime + " End: " + endDateTime);

    }

    scanner.close();

    analyze(installation.getStartDate(), installation.getEndDate());

}

From source file:eu.europa.ec.fisheries.uvms.rules.service.business.AbstractFact.java

License:Open Source License

/**
 * Message creation date/time not in the past.
 *
 * @param creationDate The Message creation date/time to be verified.
 * @param minutes      A threshold in minutes to compensate for incorrect clock synchronization of the exchanging systems.
 *//*w  w  w . jav a2  s.  c o m*/
public boolean dateNotInPast(Date creationDate, int minutes) {

    boolean notInPast = true;
    if (creationDate != null) {
        DateTime now = eu.europa.ec.fisheries.uvms.commons.date.DateUtils.nowUTC();
        log.debug("now is {}", now.toString());
        now = now.plusMinutes(minutes);
        DateTime creationDateUTC = new DateTime(creationDate).toDateTime(DateTimeZone.UTC);
        log.debug("creationDate is {}", creationDateUTC.toString());
        notInPast = !creationDateUTC.toDate().before(now.toDate());
    }
    return notInPast;
}

From source file:eu.hydrologis.jgrass.geonotes.GeonotesHandler.java

License:Open Source License

/**
 * Fetches a gps coordinate from the database nearest to a supplied time and date.
 * //from w w w .  j  a  v a 2s.c  o m
 * @param dateTime the time to search for.
 * @return the coordinate of the nearest time.
 * @throws Exception
 */
public static Coordinate getGpsCoordinateForTimeStamp(DateTime dateTime, int minutesThreshold)
        throws Exception {
    DateTime from = dateTime.minusMinutes(minutesThreshold);
    DateTime to = dateTime.plusMinutes(minutesThreshold);

    Session session = null;
    try {
        session = DatabasePlugin.getDefault().getActiveDatabaseConnection().openSession();
        Criteria criteria = session.createCriteria(GpsLogTable.class);
        String utcTimeStr = "utcTime";
        criteria.add(between(utcTimeStr, from, to));
        criteria.addOrder(asc(utcTimeStr));

        List<GpsLogTable> resultsList = criteria.list();
        for (int i = 0; i < resultsList.size() - 1; i++) {

            GpsLogTable gpsLog1 = resultsList.get(i);
            GpsLogTable gpsLog2 = resultsList.get(i + 1);

            DateTime utcTimeBefore = gpsLog1.getUtcTime();
            DateTime utcTimeAfter = gpsLog2.getUtcTime();

            Interval interval = new Interval(utcTimeBefore, utcTimeAfter);
            if (interval.contains(dateTime)) {
                // take the nearest
                Interval intervalBefore = new Interval(utcTimeBefore, dateTime);
                Interval intervalAfter = new Interval(dateTime, utcTimeAfter);
                long beforeMillis = intervalBefore.toDurationMillis();
                long afterMillis = intervalAfter.toDurationMillis();
                if (beforeMillis < afterMillis) {
                    Coordinate coord = new Coordinate(gpsLog1.getEast(), gpsLog1.getNorth());
                    return coord;
                } else {
                    Coordinate coord = new Coordinate(gpsLog2.getEast(), gpsLog2.getNorth());
                    return coord;
                }
            }

        }
    } finally {
        session.close();
    }
    return null;
}

From source file:fi.hsl.parkandride.back.TimeUtil.java

License:EUPL

public static DateTime roundMinutes(int resolution, DateTime dateTime) {
    int minute = dateTime.getMinuteOfHour();
    int remainder = minute % resolution;
    int roundedRem = (int) (Math.round(((double) remainder) / resolution) * resolution);
    return dateTime.plusMinutes(roundedRem - remainder).withSecondOfMinute(0).withMillisOfSecond(0);
}

From source file:gobblin.data.management.trash.TimeBasedSnapshotCleanupPolicy.java

License:Apache License

@Override
public boolean shouldDeleteSnapshot(FileStatus snapshot, Trash trash) {
    DateTime snapshotTime = Trash.TRASH_SNAPSHOT_NAME_FORMATTER.parseDateTime(snapshot.getPath().getName());
    return snapshotTime.plusMinutes(this.retentionMinutes).isBeforeNow();
}

From source file:gr.cti.android.experimentation.controller.api.HistoryController.java

License:Open Source License

private void fillMissingIntervals(TreeSet<Long> treeSet, String rollup, long toLong) {

    //TODO: add non existing intervals
    if (rollup.endsWith("d")) {
        DateTime firstDate = new DateTime(treeSet.iterator().next());

        while (firstDate.isBefore(toLong)) {
            firstDate = firstDate.plusDays(1);
            if (!treeSet.contains(firstDate.getMillis())) {
                treeSet.add(firstDate.getMillis());
            }/*from   w ww .j  a  v a2 s  .  co  m*/
        }
    } else if (rollup.endsWith("h")) {
        DateTime firstDate = new DateTime(treeSet.iterator().next());

        while (firstDate.isBefore(toLong)) {
            firstDate = firstDate.plusHours(1);
            if (!treeSet.contains(firstDate.getMillis())) {
                treeSet.add(firstDate.getMillis());
            }
        }
    } else if (rollup.endsWith("m")) {
        DateTime firstDate = new DateTime(treeSet.iterator().next());

        while (firstDate.isBefore(toLong)) {
            firstDate = firstDate.plusMinutes(1);
            if (!treeSet.contains(firstDate.getMillis())) {
                treeSet.add(firstDate.getMillis());
            }
        }
    }
}

From source file:graph.inference.module.LaterThanWorker.java

License:Open Source License

private Interval parseDate(DAGNode date, DateTime now) {
    String dateStr = date.toString();
    if (dateStr.equals("Now") || dateStr.equals("Now-Generally"))
        return new Interval(now.getMillis(), now.getMillis() + 1);
    if (dateStr.equals("Today-Indexical"))
        return new Interval(now.dayOfYear().roundFloorCopy(), now.dayOfYear().roundCeilingCopy());
    if (dateStr.equals("Tomorrow-Indexical")) {
        return new Interval(now.plusDays(1).dayOfYear().roundFloorCopy(),
                now.plusDays(1).dayOfYear().roundCeilingCopy());
    }//from w w w  .  j a  va 2s  .  c  o m
    if (dateStr.equals("Yesterday-Indexical")) {
        return new Interval(now.minusDays(1).dayOfYear().roundFloorCopy(),
                now.minusDays(1).dayOfYear().roundCeilingCopy());
    }
    if (dateStr.equals("TheYear-Indexical")) {
        return new Interval(now.year().roundFloorCopy(), now.year().roundCeilingCopy());
    }

    // Parse the date from the DAGNode
    String parsePattern = null;
    for (int i = DATE_PARSE_INTERVALS.length - 1; i >= 0; i--) {
        StringBuilder newPattern = new StringBuilder("(" + DATE_PARSE_INTERVALS[i]);
        if (parsePattern != null)
            newPattern.append(" " + parsePattern);
        newPattern.append(")");
        parsePattern = newPattern.toString();

        DateTimeFormatter dtf = DateTimeFormat.forPattern(parsePattern);
        try {
            DateTime dateTime = dtf.parseDateTime(dateStr);
            if (dateTime != null) {
                switch (i) {
                case 0:
                    return new Interval(dateTime.getMillis(),
                            dateTime.plusSeconds(1).minusMillis(1).getMillis());
                case 1:
                    return new Interval(dateTime.getMillis(),
                            dateTime.plusMinutes(1).minusMillis(1).getMillis());
                case 2:
                    return new Interval(dateTime.getMillis(), dateTime.plusHours(1).minusMillis(1).getMillis());
                case 3:
                    return new Interval(dateTime.getMillis(), dateTime.plusDays(1).minusMillis(1).getMillis());
                case 4:
                    return new Interval(dateTime.getMillis(),
                            dateTime.plusMonths(1).minusMillis(1).getMillis());
                case 5:
                    return new Interval(dateTime.getMillis(), dateTime.plusYears(1).minusMillis(1).getMillis());
                }
            }
        } catch (Exception e) {
        }
    }
    return null;
}

From source file:hoot.services.models.osm.Changeset.java

License:Open Source License

/**
 * Updates the expiration of this changeset in the database by modifying its closed at time
 *
 * This logic is pulled directly from the Rails port, and is meant to be executed
 * at the end of each upload process involving this changeset.  This effectively extends the
 * changeset's expiration once any data is written to it and leaves it with a shorter expiration
 * if it has been opened but had no data added to it.
 *
 * @throws Exception/*from w  w  w . j  av  a  2s .  c  o  m*/
 * @todo This method is very confusing.
 */
public void updateExpiration() throws Exception {
    final DateTime now = new DateTime();

    //SQLQuery query = new SQLQuery(conn, DbUtils.getConfiguration());

    Changesets changesetRecord = (Changesets) new SQLQuery(conn, DbUtils.getConfiguration(_mapId))
            .from(changesets).where(changesets.id.eq(getId())).singleResult(changesets);

    if (isOpen()) {
        final int maximumChangesetElements = Integer.parseInt(HootProperties.getInstance().getProperty(
                "maximumChangesetElements", HootProperties.getDefault("maximumChangesetElements")));
        Timestamp newClosedAt = null;
        assert (changesetRecord.getNumChanges() <= maximumChangesetElements);
        if (changesetRecord.getNumChanges() == maximumChangesetElements) {
            newClosedAt = new Timestamp(now.getMillis());
        } else if (changesetRecord.getNumChanges() > 0) {
            /*
             * from rails port:
             *
             * if (closed_at - created_at) > (MAX_TIME_OPEN - IDLE_TIMEOUT)
             *   self.closed_at = create_at + MAX_TIME_OPEN
             * else
             *   self.closed_at = Time.now.getutc + IDLE_TIMEOUT
             */

            final DateTime createdAt = new DateTime(changesetRecord.getCreatedAt().getTime());
            final DateTime closedAt = new DateTime(changesetRecord.getClosedAt().getTime());

            final int changesetIdleTimeout = Integer.parseInt(HootProperties.getInstance().getProperty(
                    "changesetIdleTimeoutMinutes", HootProperties.getDefault("changesetIdleTimeoutMinutes")));
            final int changesetMaxOpenTime = Integer.parseInt(HootProperties.getInstance().getProperty(
                    "changesetMaxOpenTimeHours", HootProperties.getDefault("changesetMaxOpenTimeHours")));
            //The testChangesetAutoClose option = true causes changesetIdleTimeoutMinutes and
            //changesetMaxOpenTimeHours to be interpreted in seconds rather than minutes and hours,
            //respectively.  This enables faster running of auto-close related unit tests.
            if (Boolean.parseBoolean(HootProperties.getInstance().getProperty("testChangesetAutoClose",
                    HootProperties.getDefault("testChangesetAutoClose")))) {
                final int changesetMaxOpenTimeSeconds = changesetMaxOpenTime;
                final int changesetIdleTimeoutSeconds = changesetIdleTimeout;
                if (Seconds.secondsBetween(createdAt, closedAt)
                        .getSeconds() > (changesetMaxOpenTimeSeconds - changesetIdleTimeoutSeconds)) {
                    newClosedAt = new Timestamp(createdAt.plusSeconds(changesetMaxOpenTimeSeconds).getMillis());
                } else {
                    newClosedAt = new Timestamp(now.plusSeconds(changesetIdleTimeoutSeconds).getMillis());
                }
            } else {
                final int changesetMaxOpenTimeMinutes = changesetMaxOpenTime * 60;
                final int changesetIdleTimeoutMinutes = changesetIdleTimeout;
                if (Minutes.minutesBetween(createdAt, closedAt)
                        .getMinutes() > (changesetMaxOpenTimeMinutes - changesetIdleTimeoutMinutes)) {
                    newClosedAt = new Timestamp(createdAt.plusMinutes(changesetMaxOpenTimeMinutes).getMillis());
                } else {
                    newClosedAt = new Timestamp(now.plusMinutes(changesetIdleTimeoutMinutes).getMillis());
                }
            }
        }

        if (newClosedAt != null) {
            if (new SQLUpdateClause(conn, DbUtils.getConfiguration(_mapId), changesets)
                    .where(changesets.id.eq(getId())).set(changesets.closedAt, newClosedAt).execute() != 1) {
                throw new Exception("Error updating expiration on changeset.");
            }
        }
    } else {
        //TODO: I have no idea why this code block is needed now.  It didn't use to be, but after
        //some refactoring to support the changes to marking items as reviewed in ReviewResource, it
        //now is needed.  I've been unable to track down what causes this to happen.
        if (!changesetRecord.getClosedAt().before(new Timestamp(now.getMillis()))) {
            if (new SQLUpdateClause(conn, DbUtils.getConfiguration(_mapId), changesets)
                    .where(changesets.id.eq(getId())).set(changesets.closedAt, new Timestamp(now.getMillis()))
                    .execute() != 1) {
                throw new Exception("Error updating expiration on changeset.");
            }
        }
    }
}