public static String formatDuration(long duration) { // Using Joda Time DateTime now = new DateTime(); // Now DateTime plus = now.plus(new Duration(duration * 1000)); // Define and calculate the interval of time Interval interval = new Interval(now.getMillis(), plus.getMillis()); Period period = interval.toPeriod(PeriodType.time()); // Define the period formatter for pretty printing String ampersand = " & "; PeriodFormatter pf = new PeriodFormatterBuilder().appendHours().appendSuffix(ds("hour"), ds("hours")) .appendSeparator(" ", ampersand).appendMinutes().appendSuffix(ds("minute"), ds("minutes")) .appendSeparator(ampersand).appendSeconds().appendSuffix(ds("second"), ds("seconds")).toFormatter(); return pf.print(period).trim(); }
private String prettifyDuration(String duration) { PeriodFormatter formatter = new PeriodFormatterBuilder() .appendDays().appendSuffix("d") .appendHours().appendSuffix(":") .appendMinutes().appendSuffix(":") .appendSeconds().toFormatter(); Period p = formatter.parsePeriod(duration); String day = context.getResources().getString(R.string.day_short); if(p.getDays() > 0) { return String.format("%d"+ day + " %dh %dm", p.getDays(), p.getHours(), p.getMinutes()); } else if (p.getHours() > 0) { return String.format(Locale.getDefault(), "%dh %dm", p.getHours(), p.getMinutes()); } else { return String.format(Locale.getDefault(), "%dm", p.getMinutes()); } }
private static String calculateAge(DateTime epDate) { Period period; if (epDate.isBefore(new DateTime())) { period = new Period(epDate, new DateTime()); } else { period = new Period(new DateTime(), epDate); } PeriodFormatter formatter = new PeriodFormatterBuilder() .appendYears().appendSuffix("y") .appendMonths().appendSuffix("m") .appendWeeks().appendSuffix("w") .appendDays().appendSuffix("d ") .appendHours().appendSuffix("h") .appendMinutes().appendSuffix("m") .printZeroNever().toFormatter(); return formatter.print(period); }
private Helper<Long> dateHelper() { return new Helper<Long>() { public CharSequence apply(Long arg0, Options arg1) throws IOException { PeriodFormatter formatter = new PeriodFormatterBuilder() .appendDays() .appendSuffix(" d : ") .appendHours() .appendSuffix(" h : ") .appendMinutes() .appendSuffix(" m : ") .appendSeconds() .appendSuffix(" s : ") .appendMillis() .appendSuffix(" ms") .toFormatter(); return formatter.print(new Period((arg0 * 1) / 1000000)); } }; }
/** * Return true iff input folder time is between compaction.timebased.min.time.ago and * compaction.timebased.max.time.ago. */ private boolean folderWithinAllowedPeriod(Path inputFolder, DateTime folderTime) { DateTime currentTime = new DateTime(this.timeZone); PeriodFormatter periodFormatter = getPeriodFormatter(); DateTime earliestAllowedFolderTime = getEarliestAllowedFolderTime(currentTime, periodFormatter); DateTime latestAllowedFolderTime = getLatestAllowedFolderTime(currentTime, periodFormatter); if (folderTime.isBefore(earliestAllowedFolderTime)) { LOG.info(String.format("Folder time for %s is %s, earlier than the earliest allowed folder time, %s. Skipping", inputFolder, folderTime, earliestAllowedFolderTime)); return false; } else if (folderTime.isAfter(latestAllowedFolderTime)) { LOG.info(String.format("Folder time for %s is %s, later than the latest allowed folder time, %s. Skipping", inputFolder, folderTime, latestAllowedFolderTime)); return false; } else { return true; } }
public static long parseYearMonthInterval(String value, IntervalField startField, Optional<IntervalField> endField) { IntervalField end = endField.orElse(startField); if (startField == IntervalField.YEAR && end == IntervalField.MONTH) { PeriodFormatter periodFormatter = INTERVAL_YEAR_MONTH_FORMATTER; return parsePeriodMonths(value, periodFormatter, startField, end); } if (startField == IntervalField.YEAR && end == IntervalField.YEAR) { return parsePeriodMonths(value, INTERVAL_YEAR_FORMATTER, startField, end); } if (startField == IntervalField.MONTH && end == IntervalField.MONTH) { return parsePeriodMonths(value, INTERVAL_MONTH_FORMATTER, startField, end); } throw new IllegalArgumentException("Invalid year month interval qualifier: " + startField + " to " + end); }
public static String formattedDuration(long duration) { PeriodFormatter hoursMinutes = new PeriodFormatterBuilder() .appendHours() .appendSuffix(" hr", " hrs") .appendSeparator(" ") .appendMinutes() .appendSuffix(" min", " mins") .appendSeparator(" ") .appendSeconds() .appendSuffix(" sec", " secs") .toFormatter(); Period p = new Period(duration); return hoursMinutes.print(p); }
public long getGatewayDeploymentsBackupAgeLimit() { PeriodFormatter f = (new PeriodFormatterBuilder()).appendDays().toFormatter(); String s = this.get("gateway.deployment.backup.ageLimit", "-1"); long d; try { Period e = Period.parse(s, f); d = e.toStandardDuration().getMillis(); if (d < 0L) { d = -1L; } } catch (Exception var6) { d = -1L; } return d; }
public static String periodHourMinBased(long secDuration) { PeriodFormatterBuilder builder = new PeriodFormatterBuilder(); PeriodFormatter formatter = null; String minutesAbbr = ToggApp.getApplication().getString( R.string.minutes_abbr); ; String hoursAbbr = ToggApp.getApplication().getString( R.string.hours_abbr); ; formatter = builder.printZeroAlways().minimumPrintedDigits(1) .appendHours().appendLiteral(" " + hoursAbbr + " ") .minimumPrintedDigits(2).appendMinutes() .appendLiteral(" " + minutesAbbr).toFormatter(); Period period = new Period(secDuration * 1000); return formatter.print(period.normalizedStandard()); }
@Singleton @Provides public PeriodFormatter providePeriodFormatter(Dictionary<String> dictionary) { return new PeriodFormatterBuilder() .appendYears() .appendSuffix(" " + dictionary.getTranslation("year"), " " + dictionary.getTranslation("years")) .appendSeparator(" ") .appendMonths() .appendSuffix(" " + dictionary.getTranslation("month"), " " + dictionary.getTranslation("months")) .appendSeparator(" ") .appendDays() .appendSuffix(" " + dictionary.getTranslation("day"), " " + dictionary.getTranslation("days")) .appendSeparator(" ") .appendMinutes() .appendSuffix(" " + dictionary.getTranslation("minute"), " " + dictionary.getTranslation("minutes")) .appendSeparator(" ") .appendSeconds() .appendSuffix(" " + dictionary.getTranslation("second"), " " + dictionary.getTranslation("seconds")) .toFormatter(); }
private void postFailureBuild(SRunningBuild build ) { String message = ""; PeriodFormatter durationFormatter = new PeriodFormatterBuilder() .printZeroRarelyFirst() .appendHours() .appendSuffix(" hour", " hours") .appendSeparator(" ") .printZeroRarelyLast() .appendMinutes() .appendSuffix(" minute", " minutes") .appendSeparator(" and ") .appendSeconds() .appendSuffix(" second", " seconds") .toFormatter(); Duration buildDuration = new Duration(1000*build.getDuration()); message = String.format("Project '%s' build failed! ( %s )" , build.getFullName() , durationFormatter.print(buildDuration.toPeriod())); postToSlack(build, message, false); }
private void processSuccessfulBuild(SRunningBuild build) { String message = ""; PeriodFormatter durationFormatter = new PeriodFormatterBuilder() .printZeroRarelyFirst() .appendHours() .appendSuffix(" hour", " hours") .appendSeparator(" ") .printZeroRarelyLast() .appendMinutes() .appendSuffix(" minute", " minutes") .appendSeparator(" and ") .appendSeconds() .appendSuffix(" second", " seconds") .toFormatter(); Duration buildDuration = new Duration(1000*build.getDuration()); message = String.format("Project '%s' built successfully in %s." , build.getFullName() , durationFormatter.print(buildDuration.toPeriod())); postToSlack(build, message, true); }
/** * Return true iff input folder time is between compaction.timebased.min.time.ago and * compaction.timebased.max.time.ago. */ protected boolean folderWithinAllowedPeriod(Path inputFolder, DateTime folderTime) { DateTime currentTime = new DateTime(this.timeZone); PeriodFormatter periodFormatter = getPeriodFormatter(); DateTime earliestAllowedFolderTime = getEarliestAllowedFolderTime(currentTime, periodFormatter); DateTime latestAllowedFolderTime = getLatestAllowedFolderTime(currentTime, periodFormatter); if (folderTime.isBefore(earliestAllowedFolderTime)) { log.info(String.format("Folder time for %s is %s, earlier than the earliest allowed folder time, %s. Skipping", inputFolder, folderTime, earliestAllowedFolderTime)); return false; } else if (folderTime.isAfter(latestAllowedFolderTime)) { log.info(String.format("Folder time for %s is %s, later than the latest allowed folder time, %s. Skipping", inputFolder, folderTime, latestAllowedFolderTime)); return false; } else { return true; } }
@Test public void testRecompactionConditionBasedOnDuration() { RecompactionConditionFactory factory = new RecompactionConditionBasedOnDuration.Factory(); RecompactionCondition conditionBasedOnDuration = factory.createRecompactionCondition(dataset); DatasetHelper helper = mock (DatasetHelper.class); when(helper.getDataset()).thenReturn(dataset); PeriodFormatter periodFormatter = new PeriodFormatterBuilder().appendMonths().appendSuffix("m").appendDays().appendSuffix("d").appendHours() .appendSuffix("h").appendMinutes().appendSuffix("min").toFormatter(); DateTime currentTime = getCurrentTime(); Period period_A = periodFormatter.parsePeriod("11h59min"); DateTime earliest_A = currentTime.minus(period_A); when(helper.getEarliestLateFileModificationTime()).thenReturn(Optional.of(earliest_A)); when(helper.getCurrentTime()).thenReturn(currentTime); Assert.assertEquals(conditionBasedOnDuration.isRecompactionNeeded(helper), false); Period period_B = periodFormatter.parsePeriod("12h01min"); DateTime earliest_B = currentTime.minus(period_B); when(helper.getEarliestLateFileModificationTime()).thenReturn(Optional.of(earliest_B)); when(helper.getCurrentTime()).thenReturn(currentTime); Assert.assertEquals(conditionBasedOnDuration.isRecompactionNeeded(helper), true); }
public static String toAge(Date from, Date to) { if (from == null || to == null) return "N/A"; final Period period = new Period(from.getTime(), to.getTime()); DurationFieldType[] dtf = new ArrayList<DurationFieldType>() {{ add(DurationFieldType.years()); add(DurationFieldType.months()); add(DurationFieldType.days()); if (period.getYears() == 0 && period.getMonths() == 0 && period.getDays() == 0) { add(DurationFieldType.hours()); add(DurationFieldType.minutes()); } }}.toArray(new DurationFieldType[0]); PeriodFormatter pf = PeriodFormat.getDefault(); return pf.print(period.normalizedStandard(PeriodType.forFields(dtf))); }
@Provides @Singleton AsyncHttpClientConfig provideAsyncHttpClientConfig( @Named(ZERG_CONNECTION_TIMEOUT_PROPERTY) Duration connectionTimeout, @Named(ZERG_REQUEST_TIMEOUT_PROPERTY) Duration requestTimeout) { PeriodFormatter formatter = PeriodFormat.getDefault(); log.info("Using connection timeout {} and request timeout {}", formatter.print(connectionTimeout.toPeriod()), formatter.print(requestTimeout.toPeriod())); return new AsyncHttpClientConfig.Builder() .setAllowPoolingConnection(true) .setConnectionTimeoutInMs(Ints.saturatedCast(connectionTimeout.getMillis())) .setRequestTimeoutInMs(Ints.saturatedCast(requestTimeout.getMillis())) .setFollowRedirects(true) .setMaximumNumberOfRedirects(3) .setMaxRequestRetry(1) .build(); }
@Test public void testDurations() { DateTime start = org.joda.time.DateTime.now(DateTimeZone.UTC); long timeout = 1000; try { Thread.sleep(timeout); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } DateTime finish = org.joda.time.DateTime.now(DateTimeZone.UTC); Interval interval = new Interval(start, finish); Period toPeriod = interval.toPeriod(); PeriodFormatter daysHoursMinutes = new PeriodFormatterBuilder() .appendDays() .appendSuffix(" day", " days") .appendSeparator(" and ") .appendMinutes() .appendSuffix(" minute", " minutes") .appendSeparator(" and ") .appendSeconds() .appendSuffix(" second", " seconds") .toFormatter(); logger.info("[{}]", daysHoursMinutes.print(toPeriod)); }
@Override public void success() { jobExecution.setEndDate(Instant.now()); jobExecution.setStatus(SUCCESS); jobExecution.setProgressInt(jobExecution.getProgressMax()); Duration yourDuration = Duration.millis(timeRunning()); Period period = yourDuration.toPeriod(); PeriodFormatter periodFormatter = new PeriodFormatterBuilder().appendDays() .appendSuffix("d ") .appendHours() .appendSuffix("h ") .appendMinutes() .appendSuffix("m ") .appendSeconds() .appendSuffix("s ") .appendMillis() .appendSuffix("ms ") .toFormatter(); String timeSpent = periodFormatter.print(period); JOB_EXECUTION_LOG.info("Execution successful. Time spent: {}", timeSpent); sendEmail(jobExecution.getSuccessEmail(), jobExecution.getType() + " job succeeded.", jobExecution.getLog()); update(); JobExecutionContext.unset(); }
public void addDuration(Duration value, int columnNumber) { HSSFRow currentRow = getRow(); HSSFCell cell = currentRow.createCell(columnNumber); PeriodFormatter fmt = new PeriodFormatterBuilder().printZeroAlways().appendHours().appendSeparator(":").minimumPrintedDigits(2) .appendMinutes().toFormatter(); MutablePeriod valueFormatted = new MutablePeriod(value.getMillis(), PeriodType.time()); if (value.toPeriod().getMinutes() < 0) { valueFormatted.setMinutes(-value.toPeriod().getMinutes()); if (value.toPeriod().getHours() == 0) { fmt = new PeriodFormatterBuilder().printZeroAlways().appendLiteral("-").appendHours().appendSeparator(":") .minimumPrintedDigits(2).appendMinutes().toFormatter(); } } cell.setCellValue(fmt.print(valueFormatted)); cell.setCellStyle(getExcelStyle(excelStyle.getValueStyle(), wrapText)); }
private Period getSessionMaxAge() { String maxAge = environment.getRequiredProperty("auth.session.maxAge"); PeriodFormatter format = new PeriodFormatterBuilder() .appendDays() .appendSuffix("d", "d") .printZeroRarelyFirst() .appendHours() .appendSuffix("h", "h") .printZeroRarelyFirst() .appendMinutes() .appendSuffix("m", "m") .toFormatter(); Period sessionMaxAge = format.parsePeriod(maxAge); if (LOG.isDebugEnabled()) { LOG.debug("Session maxAge is: "+ formatIfNotZero(sessionMaxAge.getDays(), "days", "day") + formatIfNotZero(sessionMaxAge.getHours(), "hours", "hour") + formatIfNotZero(sessionMaxAge.getMinutes(), "minutes", "minute") ); } return sessionMaxAge; }
/** * Converts the duration in the format of HH:MM:SS:ss to HH:MM:SS * @param periodHHMMSSmm * @return */ public static String convertDuration(final String periodHHMMSSmm){ String newDuration = periodHHMMSSmm; PeriodFormatter hoursMinutesSecondsMilli = new PeriodFormatterBuilder() .appendHours() .appendSeparator(":") .appendMinutes() .appendSeparator(":") .appendSeconds() .appendSeparator(":") .appendMillis() .toFormatter(); try{ if (StringUtils.isNotBlank(periodHHMMSSmm)){ Period period = hoursMinutesSecondsMilli.parsePeriod(periodHHMMSSmm); newDuration = String.format("%02d:%02d:%02d", period.getHours(), period.getMinutes(), period.getSeconds()); } }catch(IllegalArgumentException e){ log.error("Invalid duration format: " + periodHHMMSSmm); } return newDuration; }
public long parseToLong(String interval) { for (PeriodFormatter f : ALL) { try { return f.parsePeriod(interval).toStandardDuration().getMillis(); } catch (IllegalArgumentException e) { //ommit } } return DEFAULT; }
public static String getDiffFormatted(Date from, Date to) { Duration duration = new Duration(to.getTime() - from.getTime()); // in // milliseconds PeriodFormatter formatter = new PeriodFormatterBuilder().printZeroNever()// .appendWeeks().appendSuffix("w").appendSeparator(" ")// .appendDays().appendSuffix("d").appendSeparator(" ")// .appendHours().appendSuffix("h").appendSeparator(" ")// .appendMinutes().appendSuffix("m").appendSeparator(" ")// .appendSeconds().appendSuffix("s")// .toFormatter(); String fullTimeAgo = formatter.print(duration.toPeriod(PeriodType.yearMonthDayTime())); return Arrays.stream(fullTimeAgo.split(" ")).limit(2).collect(Collectors.joining(" ")); }
/** * Format a duration (in seconds) as hh:mm * * @param duration The duration in seconds * @return The duration formatted as hh:mm string */ @SuppressLint("DefaultLocale") public static String formatDuration(Period duration) { // to minutes PeriodFormatter hhmm = new PeriodFormatterBuilder() .printZeroAlways() .minimumPrintedDigits(2) // gives the '01' .appendHours() .appendSeparator(":") .appendMinutes() .toFormatter(); return duration.toString(hhmm); }
public static String convertMillisecondToMinutesAndSecond(long milliseconds) { Duration duration = new Duration(milliseconds); Period period = duration.toPeriod(); PeriodFormatter minutesAndSeconds = new PeriodFormatterBuilder() .printZeroAlways() .appendMinutes() .appendSeparator(":") .appendSeconds() .toFormatter(); return minutesAndSeconds.print(period); }
private int convertTime(String time) { PeriodFormatter formatter = ISOPeriodFormat.standard(); Period p = formatter.parsePeriod(time); Seconds s = p.toStandardSeconds(); return s.getSeconds(); }
public String getFormattedDuration() { int duration; try { duration = Integer.parseInt(this.duration); } catch (NumberFormatException e) { return "?"; } Period period = Duration.standardSeconds(duration).toPeriod(); PeriodFormatter formatter = (period.getHours() > 0) ? hourPeriodFormatter : secondsPeriodFormatter; return period.toString(formatter); }
public static String getTimestamp(long duration) { PeriodFormatter periodFormatter = new PeriodFormatterBuilder() .appendYears().appendSuffix("y ") .appendMonths().appendSuffix("m ") .appendWeeks().appendSuffix("w ") .appendDays().appendSuffix("d ") .appendHours().appendSuffix("h ") .appendMinutes().appendSuffix("m ") .appendSeconds().appendSuffix("s") .toFormatter(); return periodFormatter.print(new Period(new Duration(duration)).normalizedStandard()); }
public Period getPeriodProperty(String key, PeriodFormatter formatter, ContextProperties defaults) { Period value = typedProperties.getPeriodProperty(key, formatter); if (value != null) { return value; } else { return typedAllPropertiesFactory.create(defaults) .getPeriodProperty(key); } }
public Duration getDurationProperty(String key, PeriodFormatter formatter, ContextProperties defaults) { Duration value = typedProperties.getDurationProperty(key, formatter); if (value != null) { return value; } else { return typedAllPropertiesFactory.create(defaults) .getDurationProperty(key, formatter); } }
/** * String to period. * * @param s the s * @return the period * @throws MotuConverterException the motu converter exception */ public static Period stringToPeriod(String s) throws MotuConverterException { if (LOG.isDebugEnabled()) { LOG.debug("stringToPeriod(String) - entering"); } Period period = null; StringBuffer stringBuffer = new StringBuffer(); for (PeriodFormatter periodFormatter : DateUtils.PERIOD_FORMATTERS.values()) { try { period = periodFormatter.parsePeriod(s); } catch (IllegalArgumentException e) { // LOG.error("stringToPeriod(String)", e); stringBuffer.append(e.getMessage()); stringBuffer.append("\n"); } if (period != null) { break; } } if (period == null) { throw new MotuConverterException( String.format("Cannot convert '%s' to Period. Format '%s' is not valid.\nAcceptable format are '%s'", s, stringBuffer.toString(), DateUtils.PERIOD_FORMATTERS.keySet().toString())); } if (LOG.isDebugEnabled()) { LOG.debug("stringToPeriod(String) - exiting"); } return period; }
@Override public void run() { Duration duration = new Duration(Activator.getCountDownTime()); if (duration.getMillis() <= 0) { countDownTimer.cancel(); return; } duration = duration.minus(1000); Activator.setCountDownTime(duration.getMillis()); final Period periodLeft = duration.toPeriod(); PeriodFormatter formatter = new PeriodFormatterBuilder().minimumPrintedDigits(2).printZeroAlways().appendHours() .appendSeparator(":").minimumPrintedDigits(2).printZeroAlways().appendMinutes().appendSeparator(":") .minimumPrintedDigits(2).printZeroAlways().appendSeconds().toFormatter(); String formattedTime = periodLeft.toString(formatter); Runnable updateUi = () -> { int hours = periodLeft.getHours(); int mins = periodLeft.getMinutes(); int seconds = periodLeft.getSeconds(); NumberFormat numberFormat = new DecimalFormat("00"); CountDownTimerPage.hourCountDownLabel.setText(numberFormat.format(hours)); CountDownTimerPage.minuteCountDownLabel.setText(numberFormat.format(mins)); CountDownTimerPage.secondsCountDownLabel.setText(numberFormat.format(seconds)); }; Display.getDefault().asyncExec(updateUi); Job countDownJob = new CountDownJob("countdown", formattedTime); countDownJob.schedule(); }
@Override public void serialize( final Duration duration, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException { if (duration == null) { jgen.writeNull(); return; } final PeriodFormatter formatter = ISOPeriodFormat.standard(); jgen.writeString(duration.toPeriod().toString(formatter)); }
@Override public Duration deserialize(final JsonParser parser, final DeserializationContext ctxt) throws JsonParseException, IOException { final JsonToken jsonToken = parser.getCurrentToken(); if (jsonToken == JsonToken.VALUE_NUMBER_INT) { return new Duration(parser.getLongValue()); } else if (jsonToken == JsonToken.VALUE_STRING) { final String str = parser.getText().trim(); if (str.length() == 0) { return null; } final PeriodFormatter formatter = ISOPeriodFormat.standard(); return formatter.parsePeriod(str).toStandardDuration(); } throw ctxt.mappingException(Duration.class); }
/** * Generic method to convert the milliseconds into the elapsed time string. * * @param start Start timestamp. * @param finish End timestamp. * @return String representation of the elapsed time. */ public static String timeToString(long start, long finish) { Duration duration = new Duration(finish - start); // in milliseconds PeriodFormatter formatter = new PeriodFormatterBuilder().appendDays().appendSuffix("d") .appendHours().appendSuffix("h").appendMinutes().appendSuffix("m").appendSeconds() .appendSuffix("s").appendMillis().appendSuffix("ms").toFormatter(); return formatter.print(duration.toPeriod()); }
private Optional<Long> getEarliestAllowedTimestamp() { if (!this.properties.contains(TIME_PARTITIONED_WRITER_MAX_TIME_AGO)) { return Optional.<Long> absent(); } else { DateTime currentTime = new DateTime(this.timeZone); PeriodFormatter periodFormatter = getPeriodFormatter(); String maxTimeAgoStr = this.properties.getProp(TIME_PARTITIONED_WRITER_MAX_TIME_AGO); Period maxTimeAgo = periodFormatter.parsePeriod(maxTimeAgoStr); return Optional.of(currentTime.minus(maxTimeAgo).getMillis()); } }
private String getFormattedDuration(int seconds) { Period period = new Period(Seconds.seconds(seconds)); PeriodFormatter periodFormatter = new PeriodFormatterBuilder() .printZeroAlways() .minimumPrintedDigits(2) .appendHours() .appendSeparator(":") .appendMinutes() .appendSeparator(":") .appendSeconds() .toFormatter(); return periodFormatter.print(period.normalizedStandard()); }