Example usage for org.joda.time Period getSeconds

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

Introduction

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

Prototype

public int getSeconds() 

Source Link

Document

Gets the seconds field part of the period.

Usage

From source file:com.mobileman.kuravis.core.util.DateTimeUtils.java

License:Apache License

/**
 * @param date//w  w  w  . ja  v  a 2s  . c  o m
 * @return formatted elapsed time from now
 */
public static String fmtElapsedTime(Date date) {
    if (date == null) {
        return "";
    }
    Period period = new Period(date.getTime(), Calendar.getInstance().getTimeInMillis());
    PeriodFormatterBuilder pf = new PeriodFormatterBuilder();
    pf.appendPrefix(" vor ");
    if (period.getYears() > 0) {
        pf.appendYears().appendSuffix(" Jahr", " Jahren");
    } else if (period.getMonths() > 0) {
        pf.appendMonths().appendSuffix(" Monat", " Monaten");
    } else if (period.getWeeks() > 0) {
        pf.appendWeeks().appendSuffix(" Woche ", " Wochen");
    } else if (period.getDays() > 0) {
        pf.appendDays().appendSuffix(" Tag ", " Tagen");
    } else if (period.getHours() > 0) {
        pf.appendHours().appendSuffix(" Stunde ", " Stunden");
    } else if (period.getMinutes() > 0) {
        pf.appendMinutes().appendSuffix(" Minute ", " Minuten");
    } else if (period.getSeconds() > 0) {
        pf.appendSeconds().appendSuffix(" Sekunde ", " Sekunden");
    }
    return pf.toFormatter().print(period);
}

From source file:com.mycompany.ajaxandxml.ws.DurationAdapter.java

@Override
public String marshal(Period v) throws Exception {
    return v.getHours() + " hour " + v.getMinutes() + " minutes and " + v.getSeconds() + " seconds";
}

From source file:com.nestedbird.components.bridges.JodaPeriodSplitBridge.java

License:Open Source License

@Override
public String objectToString(final Object value) {
    final Period period = (Period) Optional.ofNullable(value).orElse(new Period(0));

    return String.valueOf(period.getSeconds());
}

From source file:com.sap.dirigible.runtime.metrics.TimeUtils.java

License:Open Source License

private static DateTime dateTimeCeiling(DateTime dt, Period p) {
    if (p.getYears() != 0) {
        return dt.yearOfEra().roundCeilingCopy().minusYears(dt.getYearOfEra() % p.getYears());
    } else if (p.getMonths() != 0) {
        return dt.monthOfYear().roundCeilingCopy().minusMonths((dt.getMonthOfYear() - 1) % p.getMonths());
    } else if (p.getWeeks() != 0) {
        return dt.weekOfWeekyear().roundCeilingCopy().minusWeeks((dt.getWeekOfWeekyear() - 1) % p.getWeeks());
    } else if (p.getDays() != 0) {
        return dt.dayOfMonth().roundCeilingCopy().minusDays((dt.getDayOfMonth() - 1) % p.getDays());
    } else if (p.getHours() != 0) {
        return dt.hourOfDay().roundCeilingCopy().minusHours(dt.getHourOfDay() % p.getHours());
    } else if (p.getMinutes() != 0) {
        return dt.minuteOfHour().roundCeilingCopy().minusMinutes(dt.getMinuteOfHour() % p.getMinutes());
    } else if (p.getSeconds() != 0) {
        return dt.secondOfMinute().roundCeilingCopy().minusSeconds(dt.getSecondOfMinute() % p.getSeconds());
    }/* w  w w  .j a v  a 2  s  .  c  o m*/
    return dt.millisOfSecond().roundCeilingCopy().minusMillis(dt.getMillisOfSecond() % p.getMillis());
}

From source file:com.spotify.helios.cli.Output.java

License:Apache License

public static String humanDuration(final Duration dur) {
    final Period p = dur.toPeriod().normalizedStandard();

    if (dur.getStandardSeconds() == 0) {
        return "0 seconds";
    } else if (dur.getStandardSeconds() < 60) {
        return format("%d second%s", p.getSeconds(), p.getSeconds() > 1 ? "s" : "");
    } else if (dur.getStandardMinutes() < 60) {
        return format("%d minute%s", p.getMinutes(), p.getMinutes() > 1 ? "s" : "");
    } else if (dur.getStandardHours() < 24) {
        return format("%d hour%s", p.getHours(), p.getHours() > 1 ? "s" : "");
    } else {/*from  w w  w  .  ja v  a 2s .  co  m*/
        return format("%d day%s", dur.getStandardDays(), dur.getStandardDays() > 1 ? "s" : "");
    }
}

From source file:com.thinkbiganalytics.scheduler.util.TimerToCronExpression.java

License:Apache License

private static String getSecondsCron(Period p) {
    Integer sec = p.getSeconds();
    Seconds s = p.toStandardSeconds();//from  w ww . ja v  a2s  . c  o m
    Integer seconds = s.getSeconds();
    String str = "0" + (sec > 0 ? "/" + sec : "");
    if (seconds > 60) {
        str = sec + "";
    }
    return str;
}

From source file:edu.jhu.hlt.concrete.stanford.Runner.java

License:Open Source License

/**
 * @param args/*from   w  w  w.j  a  va  2s . c o  m*/
 */
public static void main(String... args) {
    Thread.setDefaultUncaughtExceptionHandler(new LoggedUncaughtExceptionHandler());

    Runner run = new Runner();
    JCommander jc = new JCommander(run, args);
    jc.setProgramName(Runner.class.getName());
    if (run.help) {
        jc.usage();
        System.exit(0);
    }

    int nDocsSeen = 0;
    int nDocsFailed = 0;
    List<String> exIds = new ArrayList<>();
    boolean haveSeenException = false;

    Path outF = Paths.get(run.outputPath);
    Path inp = Paths.get(run.inputPath);
    LOGGER.info("Input path: {}", inp.toString());
    LOGGER.info("Output folder: {}", outF.toString());

    try {
        new ExistingNonDirectoryFile(inp);
        if (!Files.exists(outF)) {
            LOGGER.info("Creating output directory.");
            Files.createDirectories(outF);
        }

        Path outFile = outF.resolve(run.outputName);
        if (Files.exists(outFile)) {
            if (run.overwrite)
                Files.delete(outFile);
            else {
                LOGGER.info("File exists and overwrite = false. Not continuing.");
                System.exit(1);
            }
        }

        PipelineLanguage lang = PipelineLanguage.getEnumeration(run.lang);
        Analytic<? extends WrappedCommunication> a;
        if (run.isInputTokenized)
            a = new AnnotateTokenizedConcrete(lang);
        else
            a = new AnnotateNonTokenizedConcrete(lang);

        StopWatch sw = new StopWatch();
        sw.start();
        LOGGER.info("Beginning ingest at: {}", new DateTime().toString());
        try (InputStream in = Files.newInputStream(inp);
                OutputStream os = Files.newOutputStream(outFile);
                GzipCompressorOutputStream gout = new GzipCompressorOutputStream(os);
                TarArchiver arch = new TarArchiver(gout);) {
            TarGzArchiveEntryCommunicationIterator iter = new TarGzArchiveEntryCommunicationIterator(in);
            while (iter.hasNext()) {
                Communication c = iter.next();
                nDocsSeen++;
                try {
                    arch.addEntry(new ArchivableCommunication(a.annotate(c).getRoot()));
                } catch (AnalyticException e) {
                    LOGGER.warn("Caught analytic exception on document: " + c.getId());
                    nDocsFailed++;
                    exIds.add(c.getId());
                    haveSeenException = true;
                    if (run.exitOnException)
                        break;
                }
            }
        }

        if (run.exitOnException && haveSeenException)
            System.exit(1);

        sw.stop();
        LOGGER.info("Ingest completed at: {}", new DateTime().toString());
        Duration d = new Duration(sw.getTime());
        Period p = d.toPeriod();
        LOGGER.info("Ingest took {}d{}m{}s.", p.getDays(), p.getMinutes(), p.getSeconds());
        final int seenLessFailed = nDocsSeen - nDocsFailed;
        float ratio = nDocsSeen > 0 ? (float) seenLessFailed / nDocsSeen * 100 : 0;
        LOGGER.info("Converted {}% of documents successfully. [{} / {} total]", ratio, seenLessFailed,
                nDocsSeen);
        if (haveSeenException)
            exIds.forEach(eid -> LOGGER.info("Caught exception on document: {}", eid));
    } catch (IOException | NotFileException e) {
        throw new RuntimeException(e);
    }
}

From source file:eu.vranckaert.worktime.activities.reporting.ReportingExportActivity.java

License:Apache License

/**
 * Create a {@link Date} instance based on a calculated {@link Period} (aka time-duration) that Excel can handle to
 * display a date.<br/>/*www.j  a  va  2s.c o  m*/
 * Basically this means that a {@link Date} will be generated for time zone GMT+0 and the default date will be:
 * <b>31/11/1899 00:00:00,00000</b>. To this date the hours, minutes and seconds of the {@link Period} will be
 * added.
 *
 * @param period The period (or time duration) that will need to be converted to an Excel date.
 * @return The Excel date that will be x hours, x minutes and x seconds after 31/11/1899 00:00:00,00000.
 */
private Date getExcelTimeFromPeriod(Period period) {
    Log.d(getApplicationContext(), LOG_TAG, "Creating excel calendar date-time for period " + period);

    /*
     * Specifying the GMT+0 time zone for the Excel calendar fixes the issue that for each excel time displayed a
     * certain amount of hours (always the same amount of hours for all the calculated excel times) is missing.
     * The reason for this is that the Calendar takes the device default time zone (for the emulator being GMT+0 by
     * default). For your own device that could be GMT+01:00. However Excel only works with GMT+0 time zones, if
     * that's not the case it translates the time to the GMT+0 time zone and you loose one hour for every generated
     * Excel time.
     */
    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+00:00"));
    cal.set(Calendar.YEAR, 1899);
    cal.set(Calendar.MONTH, 11);
    cal.set(Calendar.DAY_OF_MONTH, 31);
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    //cal.add(Calendar.HOUR, -36);

    Log.d(getApplicationContext(), LOG_TAG, "Default excel calendar before adding time: " + cal.getTime());

    int hours = period.getHours();
    int minutes = period.getMinutes();
    int seconds = period.getSeconds();

    if (hours > 0) {
        Log.d(getApplicationContext(), LOG_TAG, "About to add hours to the excel calendar...");
        cal.add(Calendar.HOUR, hours);
        Log.d(getApplicationContext(), LOG_TAG, "Default excel calendar after adding hours: " + cal.getTime());
    }
    if (minutes > 0) {
        Log.d(getApplicationContext(), LOG_TAG, "About to add minutes to the excel calendar...");
        cal.set(Calendar.MINUTE, minutes);
        Log.d(getApplicationContext(), LOG_TAG,
                "Default excel calendar after adding minutes: " + cal.getTime());
    }
    if (seconds > 0) {
        Log.d(getApplicationContext(), LOG_TAG, "About to add seconds to the excel calendar...");
        cal.set(Calendar.SECOND, seconds);
        Log.d(getApplicationContext(), LOG_TAG,
                "Default excel calendar after adding seconds: " + cal.getTime());
    }

    return cal.getTime();
}

From source file:influent.server.utilities.DateTimeParser.java

License:MIT License

/**
 * @see http://joda-time.sourceforge.net/apidocs/org/joda/time/Period.html#normalizedStandard()
 *///from  w  ww  . j  a  v  a  2s  . c  o  m
public static Period normalize(Period period) {
    long millis = period.getMillis();
    millis += period.getSeconds() * DateTimeConstants.MILLIS_PER_SECOND;
    millis += period.getMinutes() * DateTimeConstants.MILLIS_PER_MINUTE;
    millis += period.getHours() * DateTimeConstants.MILLIS_PER_HOUR;
    millis += period.getDays() * DateTimeConstants.MILLIS_PER_DAY;
    millis += period.getWeeks() * DateTimeConstants.MILLIS_PER_WEEK;

    Period result = new Period(millis, DateTimeUtils.getPeriodType(PeriodType.standard()),
            ISOChronology.getInstanceUTC());
    int years = period.getYears();
    int months = period.getMonths();

    if (years != 0 || months != 0) {
        years = FieldUtils.safeAdd(years, months / 12);
        months = months % 12;
        if (years != 0) {
            result = result.withYears(years);
        }
        if (months != 0) {
            result = result.withMonths(months);
        }
    }

    return result;
}

From source file:io.coala.xml.XmlUtil.java

License:Apache License

/**
 * @param period// w ww.  ja v a  2  s  .c  o  m
 * @return a JAXP {@link Duration}
 */
public static Duration toDuration(final Period period) {
    return getDatatypeFactory().newDuration(true, period.getYears(), period.getMonths(), period.getDays(),
            period.getHours(), period.getMinutes(), period.getSeconds());
}