Example usage for org.joda.time Period Period

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

Introduction

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

Prototype

private Period(int[] values, PeriodType type) 

Source Link

Document

Constructor used when we trust ourselves.

Usage

From source file:com.enonic.cms.core.time.BaseSystemTimeService.java

License:Open Source License

@Override
public Period upTime() {
    Period period = new Period(bootTime(), getNowAsDateTime());
    if (period.getMillis() >= 500) {
        period = period.minusMillis(period.getMillis()).plusSeconds(1);
    } else if (period.getMillis() < 500) {
        period = period.minusMillis(period.getMillis());
    }/*from  ww w  . j a va 2s.c o  m*/
    return period;
}

From source file:com.ethercis.servicemanager.common.IsoDateJoda.java

License:Apache License

/**
 * Calculate the difference from the given time to now. 
 * ISO 8601 states: Durations are represented by the format P[n]Y[n]M[n]DT[n]H[n]M[n]S
 * @param utc Given time, e.g. "1997-07-16T19:20:30.45+01:00"
 * @return The ISO 8601 Period like "P3Y6M4DT12H30M17S"
 *//*from w w  w  .jav  a2  s  . co m*/
public static String getDifferenceToNow(String utc) {
    if (utc == null)
        return "";
    utc = ReplaceVariable.replaceAll(utc, " ", "T");
    DateTime now = new DateTime();
    DateTimeFormatter f = ISODateTimeFormat.dateTimeParser();
    DateTime other = f.parseDateTime(utc);
    Period period = new Period(other, now); // Period(ReadableInstant startInstant, ReadableInstant endInstant)
    return period.toString();
}

From source file:com.github.dbourdette.glass.tools.UtilsTool.java

License:Apache License

public String duration(Date start, Date end) {
    Period period = new Period(start.getTime(), end.getTime());

    StringBuilder builder = new StringBuilder();

    appendDuration(builder, period.getDays(), "d");
    appendDuration(builder, period.getHours(), "h");
    appendDuration(builder, period.getMinutes(), "m");
    appendDuration(builder, period.getSeconds(), "s");

    return builder.toString().trim();
}

From source file:com.github.jobs.utils.RelativeDate.java

License:Apache License

/**
 * This method returns a String representing the relative
 * date by comparing the Calendar being passed in to the
 * date / time that it is right now./* w  w w  .java 2  s  .  c  om*/
 *
 * @param context used to build the string response
 * @param time    time to compare with current time
 * @return a string representing the time ago
 */
public static String getTimeAgo(Context context, long time) {
    DateTime baseDate = new DateTime(time);
    DateTime now = new DateTime();
    Period period = new Period(baseDate, now);

    if (period.getSeconds() < 0 || period.getMinutes() < 0) {
        return context.getString(R.string.just_now);
    }

    if (period.getYears() > 0) {
        int resId = period.getYears() == 1 ? R.string.one_year_ago : R.string.years_ago;
        return buildString(context, resId, period.getYears());
    }

    if (period.getMonths() > 0) {
        int resId = period.getMonths() == 1 ? R.string.one_month_ago : R.string.months_ago;
        return buildString(context, resId, period.getMonths());
    }

    if (period.getWeeks() > 0) {
        int resId = period.getWeeks() == 1 ? R.string.one_week_ago : R.string.weeks_ago;
        return buildString(context, resId, period.getWeeks());
    }

    if (period.getDays() > 0) {
        int resId = period.getDays() == 1 ? R.string.one_day_ago : R.string.days_ago;
        return buildString(context, resId, period.getDays());
    }

    if (period.getHours() > 0) {
        int resId = period.getHours() == 1 ? R.string.one_hour_ago : R.string.hours_ago;
        return buildString(context, resId, period.getHours());
    }

    if (period.getMinutes() > 0) {
        int resId = period.getMinutes() == 1 ? R.string.one_minute_ago : R.string.minutes_ago;
        return buildString(context, resId, period.getMinutes());
    }

    int resId = period.getSeconds() == 1 ? R.string.one_second_ago : R.string.seconds_ago;
    return buildString(context, resId, period.getSeconds());
}

From source file:com.github.jsdossier.Main.java

License:Apache License

private void runCompiler() {
    if (!shouldRunCompiler()) {
        System.exit(-1);//from  ww w.  ja  v a  2s  .  co m
    }

    Instant start = Instant.now();
    config.getOutputStream().println("Generating documentation...");

    int result = 0;
    try {
        result = doRun();
    } catch (FlagUsageException e) {
        System.err.println(e.getMessage());
        System.exit(-1);
    } catch (Throwable t) {
        t.printStackTrace(System.err);
        System.exit(-2);
    }

    if (result != 0) {
        System.exit(result);
    }

    DocWriter writer = new DocWriter(config, typeRegistry);
    try {
        writer.generateDocs();
        if (config.isZipOutput()) {
            config.getOutput().getFileSystem().close();
        }
    } catch (IOException e) {
        e.printStackTrace(System.err);
        System.exit(-3);
    }

    Instant stop = Instant.now();
    String output = new PeriodFormatterBuilder().appendHours().appendSuffix("h") // I hope not...
            .appendSeparator(" ").appendMinutes().appendSuffix("m").appendSeparator(" ")
            .appendSecondsWithOptionalMillis().appendSuffix("s").toFormatter().print(new Period(start, stop));

    config.getOutputStream().println("Finished in " + output);
}

From source file:com.github.rinde.logistics.pdptw.mas.comm.AuctionPanel.java

License:Apache License

AuctionPanel(AuctionCommModel<?> m) {
    model = m;// www  . jav a2 s .com
    tree = Optional.absent();

    parcelItems = new LinkedHashMap<>();

    model.getEventAPI().addListener(new Listener() {
        @Override
        public void handleEvent(final Event e) {
            final AuctionEvent ae = (AuctionEvent) e;

            tree.get().getDisplay().asyncExec(new Runnable() {
                @Override
                public void run() {
                    if (!parcelItems.containsKey(ae.getParcel())) {
                        final TreeItem item = new TreeItem(tree.get(), 0);
                        item.setText(ae.getParcel().toString());
                        parcelItems.put(ae.getParcel(), item);
                    }

                    final TreeItem parent = parcelItems.get(ae.getParcel());
                    final boolean finish = e.getEventType() == EventType.FINISH_AUCTION;

                    final TreeItem item = new TreeItem(parent, 0);
                    parent.setExpanded(true);
                    item.setText(new String[] { ae.getEventType().toString(),
                            FORMATTER.print(new Period(0, ae.getTime())),
                            finish ? ae.getWinner().get().toString() + SPACE + ae.getNumBids() : "" });

                    if (collapseButton.get().getSelection()) {
                        parent.setExpanded(!finish);
                    }
                    if (scrollButton.get().getSelection()) {
                        final TreeItem target = parent.getExpanded() ? item : parent;
                        tree.get().showItem(target);
                        tree.get().select(target);
                    }

                    final int reauctions = model.getNumAuctions() - model.getNumParcels();
                    final int perc = (int) ((reauctions - model.getNumUnsuccesfulAuctions()
                            - model.getNumFailedAuctions()) / (double) reauctions * 100d);

                    statusLabel.get()
                            .setText("# parcels: " + model.getNumParcels() + " # ongoing auctions: "
                                    + model.getNumberOfOngoingAuctions() + " reauctions: " + reauctions
                                    + " (success: " + perc + "%)");

                    statusLabel.get().setToolTipText("unsuccessful: " + model.getNumUnsuccesfulAuctions()
                            + " failed: " + model.getNumFailedAuctions());

                    statusLabel.get().pack(true);
                    statusLabel.get().getParent().redraw();
                    statusLabel.get().getParent().layout();
                }
            });

        }
    }, EventType.values());
}

From source file:com.github.rinde.rinsim.ui.SimulationViewer.java

License:Apache License

@Override
public void afterTick(final TimeLapse timeLapse) {
    if (simulator.isPlaying() && lastRefresh + timeLapse.getTimeStep() * speedUp > timeLapse.getStartTime()) {
        return;//from ww  w.  j av  a  2 s.  com
    }
    lastRefresh = timeLapse.getStartTime();
    // TODO sleep should be relative to speedUp as well?
    try {
        Thread.sleep(30);
    } catch (final InterruptedException e) {
        throw new RuntimeException(e);
    }
    if (display.isDisposed()) {
        return;
    }
    display.syncExec(new Runnable() {
        @Override
        public void run() {
            if (!canvas.isDisposed()) {
                if (simulator.getTimeStep() > 500) {
                    final String formatted = FORMATTER.print(new Period(0, simulator.getCurrentTime()));
                    timeLabel.setText(formatted);
                } else {
                    timeLabel.setText(Long.toString(simulator.getCurrentTime()));
                }
                timeLabel.pack();
                canvas.redraw();
            }
        }
    });
}

From source file:com.helger.datetime.period.DateTimePeriod.java

License:Apache License

@Nonnull
public final Period getAsPeriod() {
    if (!canConvertToPeriod())
        throw new IllegalStateException("Cannot convert to a Period!");
    return new Period(getStart(), getEnd());
}

From source file:com.helger.peppol.smpserver.ui.AppCommonUI.java

License:Apache License

@Nonnull
public static BootstrapTable createCertificateDetailsTable(@Nonnull final X509Certificate aX509Cert,
        @Nonnull final LocalDateTime aNowLDT, @Nonnull final Locale aDisplayLocale) {
    final LocalDateTime aNotBefore = PDTFactory.createLocalDateTime(aX509Cert.getNotBefore());
    final LocalDateTime aNotAfter = PDTFactory.createLocalDateTime(aX509Cert.getNotAfter());
    final PublicKey aPublicKey = aX509Cert.getPublicKey();

    final BootstrapTable aCertDetails = new BootstrapTable(HCCol.star(), HCCol.star());
    aCertDetails.addBodyRow().addCell("Version:").addCell(Integer.toString(aX509Cert.getVersion()));
    aCertDetails.addBodyRow().addCell("Subject:").addCell(aX509Cert.getSubjectX500Principal().getName());
    aCertDetails.addBodyRow().addCell("Issuer:").addCell(aX509Cert.getIssuerX500Principal().getName());
    aCertDetails.addBodyRow().addCell("Serial number:").addCell(aX509Cert.getSerialNumber().toString(16));
    aCertDetails.addBodyRow().addCell("Valid from:").addCell(
            new HCTextNode(PDTToString.getAsString(aNotBefore, aDisplayLocale) + " "),
            aNowLDT.isBefore(aNotBefore)
                    ? new BootstrapLabel(EBootstrapLabelType.DANGER).addChild("!!!NOT YET VALID!!!")
                    : null);/*from ww w .j a va  2s .co  m*/
    aCertDetails.addBodyRow().addCell("Valid to:").addCell(
            new HCTextNode(PDTToString.getAsString(aNotAfter, aDisplayLocale) + " "),
            aNowLDT.isAfter(aNotAfter)
                    ? new BootstrapLabel(EBootstrapLabelType.DANGER).addChild("!!!NO LONGER VALID!!!")
                    : new HCDiv().addChild("Valid for: " + PeriodFormatMultilingual
                            .getFormatterLong(aDisplayLocale).print(new Period(aNowLDT, aNotAfter))));

    if (aPublicKey instanceof RSAPublicKey) {
        // Special handling for RSA
        aCertDetails.addBodyRow().addCell("Public key:").addCell(aX509Cert.getPublicKey().getAlgorithm() + " ("
                + ((RSAPublicKey) aPublicKey).getModulus().bitLength() + " bits)");
    } else {
        // Usually EC or DSA key
        aCertDetails.addBodyRow().addCell("Public key:").addCell(aX509Cert.getPublicKey().getAlgorithm());
    }
    aCertDetails.addBodyRow().addCell("Signature algorithm:")
            .addCell(aX509Cert.getSigAlgName() + " (" + aX509Cert.getSigAlgOID() + ")");
    return aCertDetails;
}

From source file:com.jbirdvegas.mgerrit.search.AgeSearch.java

License:Apache License

@Override
public String[] getEscapeArgument() {
    DateTime now = new DateTime();
    Period period = mPeriod;/*w ww.ja  v a  2s  . com*/

    // Equals: we need to do some arithmetic to get a range from the period
    if ("=".equals(getOperator())) {
        if (period == null) {
            period = new Period(mInstant, Instant.now());
        }
        DateTime earlier = now.minus(adjust(period, +1));
        DateTime later = now.minus(period);
        return new String[] { earlier.toString(), later.toString() };
    } else {
        if (period == null) {
            return new String[] { mInstant.toString() };
        }
        return new String[] { now.minus(period).toString() };
    }
}