Example usage for org.joda.time Duration Duration

List of usage examples for org.joda.time Duration Duration

Introduction

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

Prototype

public Duration(ReadableInstant start, ReadableInstant end) 

Source Link

Document

Creates a duration from the given interval endpoints.

Usage

From source file:org.netxilia.spi.impl.formula.parser.ASTNumericExpression.java

License:Open Source License

private IGenericValue dateOperations(IGenericValue gvLeft, IGenericValue gvRight) {

    // D + P, P + D, D - D, D - P
    if (gvLeft.getValueType() == GenericValueType.DATE) {

        if ("+".equals(operator)) {
            // D + P
            LocalDateTime result = DateUtils
                    .toLocalDateTime(gvLeft.getDateValue(), DateValue.ORIGIN.toLocalDateTime())
                    .plus(period(gvRight.getNumberValue().doubleValue()));
            return new DateValue(result);
        }//from w  w w .  j  av a 2s.co m
        if ("-".equals(operator)) {
            if (gvRight.getValueType() == GenericValueType.DATE) {
                // D - D
                Double result = (double) (new Duration(gvRight.getDateValue().toDateTime(DateValue.ORIGIN),
                        gvLeft.getDateValue().toDateTime(DateValue.ORIGIN)).getMillis())
                        / DateTimeConstants.MILLIS_PER_DAY;
                return new NumberValue(result);
            } else {
                // D - P
                LocalDateTime result = DateUtils
                        .toLocalDateTime(gvLeft.getDateValue(), DateValue.ORIGIN.toLocalDateTime())
                        .minus(period(gvRight.getNumberValue().doubleValue()));
                return new DateValue(result);
            }
        }
        // other operations are not allowed - fall through number operations
    } else if (gvRight.getValueType() == GenericValueType.DATE) {
        if ("+".equals(operator)) {
            // P + D
            LocalDateTime result = DateUtils
                    .toLocalDateTime(gvRight.getDateValue(), DateValue.ORIGIN.toLocalDateTime())
                    .plus(period(gvLeft.getNumberValue().doubleValue()));
            return new DateValue(result);
        }
    }
    return null;

}

From source file:org.obm.icalendar.ical4jwrapper.ICalendarEvent.java

License:Open Source License

private long alarmFromStartDateToDate(Date toDate) {
    return new Duration(new DateTime(startDate()), new DateTime(toDate)).getStandardSeconds();
}

From source file:org.opendatakit.tables.sms.MsgHandler.java

License:Apache License

private boolean respondToDrSlotQuery(String phoneNum, TableProperties tp, Query query,
        ColumnProperties drSlotColumn, int drSlotDuration) {
    Set<Constraint> constraints = new HashSet<Constraint>();
    for (int i = query.getConstraintCount(); i >= 0; i--) {
        Constraint c = query.getConstraint(i);
        if (c.getColumnDbName().equals(drSlotColumn.getElementKey())) {
            constraints.add(c);/*from   w w w.ja  v  a 2  s  . com*/
            query.removeConstraint(i);
        }
    }
    query.setOrderBy(Query.SortOrder.ASCENDING, drSlotColumn);
    DbTable dbt = DbTable.getDbTable(dbh, tp);
    UserTable table = dbt.getRaw(query, new String[] { drSlotColumn.getElementKey() });
    // TODO: range should not be slash-separated but stored as two columns OR json in db...
    List<String[]> rawRanges = new ArrayList<String[]>();
    for (int i = 0; i < table.getNumberOfRows(); i++) {
        rawRanges.add(table.getData(i, 0).split("/"));
    }
    String earlyDate = null;
    String lateDate = null;
    for (int i = 0; i < query.getConstraintCount(); i++) {
        Constraint c = query.getConstraint(i);
        if (c.getComparisonCount() == 2) {
            String[] range;
            if (c.getComparator(0) == Query.Comparator.LESS_THAN) {
                range = new String[] { c.getValue(0), c.getValue(1) };
            } else {
                range = new String[] { c.getValue(1), c.getValue(0) };
            }
            boolean inserted = false;
            for (int j = 0; j < rawRanges.size(); j++) {
                if (range[0].compareTo(rawRanges.get(j)[0]) < 0) {
                    rawRanges.add(j, range);
                    inserted = true;
                    break;
                }
            }
            if (!inserted) {
                rawRanges.add(range);
            }
        } else if (c.getComparator(0) == Query.Comparator.LESS_THAN) {
            if (lateDate == null) {
                lateDate = c.getValue(0);
            } else if (c.getValue(0).compareTo(lateDate) < 0) {
                lateDate = c.getValue(0);
            }
        } else if (c.getComparator(0) == Query.Comparator.GREATER_THAN) {
            if (earlyDate == null) {
                earlyDate = c.getValue(0);
            } else if (c.getValue(0).compareTo(earlyDate) > 0) {
                earlyDate = c.getValue(0);
            }
        }
    }
    if (earlyDate != null) {
        rawRanges.add(new String[] { null, earlyDate });
    }
    if (lateDate != null) {
        for (int j = 0; j < rawRanges.size(); j++) {
            if (lateDate.compareTo(rawRanges.get(j)[0]) < 0) {
                rawRanges.add(j, new String[] { lateDate, null });
                break;
            }
        }
    }
    if (rawRanges.isEmpty()) {
        String resp = "anytime";
        smsSender.sendSMSWithCutoff(phoneNum, resp);
        return true;
    }
    List<String[]> ranges = new ArrayList<String[]>();
    ranges.add(rawRanges.get(0));
    for (int i = 1; i < rawRanges.size(); i++) {
        String[] lastRange = ranges.get(ranges.size() - 1);
        String[] nextRange = rawRanges.get(i);
        if (nextRange[1] == null) {
            ranges.add(nextRange);
            break;
        }
        if (nextRange[0].compareTo(lastRange[1]) > 0) {
            ranges.add(nextRange);
        } else if (nextRange[1].compareTo(lastRange[1]) > 0) {
            lastRange[1] = nextRange[1];
        }
    }
    StringBuilder sb = new StringBuilder();
    if (ranges.get(0)[0] != null) {
        DateTime dt = du.parseDateTimeFromDb(ranges.get(0)[0]);
        sb.append(";before" + du.formatShortDateTimeForUser(dt));
    }
    for (int i = 1; i < ranges.size(); i++) {
        DateTime start = du.parseDateTimeFromDb(ranges.get(i - 1)[1]);
        DateTime end = du.parseDateTimeFromDb(ranges.get(i)[0]);
        Duration duration = new Duration(start, end);
        if (duration.getStandardSeconds() >= drSlotDuration) {
            sb.append(";" + du.formatShortDateTimeForUser(start) + "-" + du.formatShortDateTimeForUser(end));
        }
    }
    if (ranges.get(ranges.size() - 1)[1] != null) {
        DateTime dt = du.parseDateTimeFromDb(ranges.get(ranges.size() - 1)[1]);
        sb.append(";after" + du.formatShortDateTimeForUser(dt));
    }
    sb.deleteCharAt(0);
    String resp = sb.toString();
    smsSender.sendSMSWithCutoff(phoneNum, resp);
    return true;
}

From source file:org.openehr.rm.datatypes.quantity.datetime.DvDuration.java

License:LGPL

/**
 * Create a Duration from two instances of DvWorldTime
 *
 * @param start/*from   w  w w. j a v  a  2  s .  co m*/
 * @param end
 */
public static DvDuration getDifference(DvTemporal start, DvTemporal end) {
    Duration d = new Duration(start.getDateTime(), end.getDateTime());
    DvDateTime dt = (DvDateTime) end;
    return new DvDuration(null, null, null, 0.0, false, null, d.toPeriodFrom(start.getDateTime()));
}

From source file:org.openhab.binding.sonos.internal.SonosZonePlayer.java

License:Open Source License

public boolean setAlarm(boolean alarmSwitch) {

    List<SonosAlarm> sonosAlarms = getCurrentAlarmList();

    if (isConfigured()) {

        // find the nearest alarm - take the current time from the Sonos System, not the system where openhab is
        // running

        String currentLocalTime = getTime();
        DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");

        DateTime currentDateTime = fmt.parseDateTime(currentLocalTime);

        Duration shortestDuration = Period.days(10).toStandardDuration();
        SonosAlarm firstAlarm = null;/*from   w w  w.j a v a2  s  .  co m*/

        for (SonosAlarm anAlarm : sonosAlarms) {
            Duration duration = new Duration(currentDateTime, anAlarm.getStartTime());
            if (anAlarm.getStartTime().isBefore(currentDateTime.plus(shortestDuration))
                    && anAlarm.getRoomUUID().equals(udn.getIdentifierString())) {
                shortestDuration = duration;
                firstAlarm = anAlarm;
            }
        }

        // Set the Alarm
        if (firstAlarm != null) {

            if (alarmSwitch) {
                firstAlarm.setEnabled(true);
            } else {
                firstAlarm.setEnabled(false);
            }

            return updateAlarm(firstAlarm);

        } else {
            return false;
        }
    } else {
        return false;
    }

}

From source file:org.opennms.netmgt.provision.service.DefaultProvisionService.java

License:Open Source License

private NodeScanSchedule createScheduleForNode(final OnmsNode node, final boolean force) {
    Assert.notNull(node, "Node may not be null");
    final String actualForeignSource = node.getForeignSource();
    if (actualForeignSource == null && !isDiscoveryEnabled()) {
        LOG.info(/*from  w w  w .  j  ava2 s.co  m*/
                "Not scheduling node {} to be scanned since it has a null foreignSource and handling of discovered nodes is disabled in provisiond",
                node);
        return null;
    }

    final String effectiveForeignSource = actualForeignSource == null ? "default" : actualForeignSource;
    try {
        final ForeignSource fs = m_foreignSourceRepository.getForeignSource(effectiveForeignSource);

        final Duration scanInterval = fs.getScanInterval();
        Duration initialDelay = Duration.ZERO;
        if (node.getLastCapsdPoll() != null && !force) {
            final DateTime nextPoll = new DateTime(node.getLastCapsdPoll().getTime()).plus(scanInterval);
            final DateTime now = new DateTime();
            if (nextPoll.isAfter(now)) {
                initialDelay = new Duration(now, nextPoll);
            }
        }

        return new NodeScanSchedule(node.getId(), actualForeignSource, node.getForeignId(), initialDelay,
                scanInterval);
    } catch (final ForeignSourceRepositoryException e) {
        LOG.warn("unable to get foreign source '{}' from repository", effectiveForeignSource, e);
        return null;
    }
}

From source file:org.openvpms.web.workspace.workflow.appointment.repeat.ScheduleEventSeries.java

License:Open Source License

/**
 * Calculates the times for the event series.
 *
 * @param series used to collect the times
 * @return the first overlapping event, or {@code null} if there are no overlaps
 *//*from   w w w .j  a va  2 s  .  co m*/
private Overlap calculateSeries(List<Times> series) {
    Overlap overlap = null;
    int index = acts.indexOf(event);
    if (current.repeats() && (acts.isEmpty() || index >= 0)) {
        Date startTime = event.getActivityStartTime();
        Date endTime = event.getActivityEndTime();
        Duration duration = new Duration(new DateTime(startTime), new DateTime(endTime));

        if (canCalculateSeries(current)) {
            List<Times> times = new ArrayList<>();
            times.add(Times.create(event));
            ListIterator<Act> iterator = (index + 1 < acts.size()) ? acts.listIterator(index + 1) : null;
            RepeatExpression expression = current.getExpression();
            RepeatCondition condition = current.getCondition();
            Predicate<Date> max = new TimesPredicate<>(maxEvents - 1);
            Predicate<Date> predicate = PredicateUtils.andPredicate(max, condition.create());
            while ((startTime = expression.getRepeatAfter(startTime, predicate)) != null) {
                endTime = new DateTime(startTime).plus(duration).toDate();
                IMObjectReference reference = null;
                if (iterator != null && iterator.hasNext()) {
                    Act act = iterator.next();
                    reference = act.getObjectReference();
                }
                Times newEvent = new Times(reference, startTime, endTime);
                overlap = getOverlap(times, newEvent);
                if (overlap != null) {
                    break;
                }
                times.add(newEvent);
                series.add(newEvent);
            }
        }
    }
    return overlap;
}

From source file:org.phenotips.jodatime.script.JodaTimeScriptService.java

License:Open Source License

/**
 * Compute the duration between two different moments.
 *
 * @param from the start moment/*w  w  w. j  a v  a 2 s.c  o  m*/
 * @param to the end moment
 * @return the difference between the two moments, or {@code null} if the parameters are invalid or the duration
 *         exceeds 64 bits
 * @see org.joda.time.Duration#Duration(ReadableInstant, ReadableInstant)
 */
public Duration getDuration(ReadableInstant from, ReadableInstant to) {
    if (from == null || to == null) {
        return null;
    }
    try {
        return new Duration(from, to);
    } catch (ArithmeticException ex) {
        return null;
    }
}