Java Code Examples for java.time.Duration#toHours()

The following examples show how to use java.time.Duration#toHours() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CacheManager.java    From plugin-installation-manager-tool with MIT License 6 votes vote down vote up
/**
 * Retrieves a json object from the cache.
 * <p>
 * Will return null if the key can't be found or if it hasn't been
 * modified for 1 hour
 *
 * @param cacheKey key to lookup, i.e. update-center
 * @return the cached json object or null
 */
JSONObject retrieveFromCache(String cacheKey) {
    Path cachedPath = cache.resolve(cacheKey + ".json");
    if (!Files.exists(cachedPath)) {
        return null;
    }

    try {
        FileTime lastModifiedTime = Files.getLastModifiedTime(cachedPath);
        Duration between = Duration.between(lastModifiedTime.toInstant(), Instant.now());
        long betweenHours = between.toHours();

        if (betweenHours > 0L) {
            if (verbose) {
                System.out.println("Cache entry expired");
            }
            return null;
        }

        return new JSONObject(new String(Files.readAllBytes(cachedPath), StandardCharsets.UTF_8));
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 2
Source File: DurationCodecTest.java    From r2dbc-mysql with Apache License 2.0 6 votes vote down vote up
private static String format(Duration d) {
    long hours = d.toHours();
    long minutes = d.minusHours(hours).toMinutes();
    long seconds = d.minusHours(hours).minusMinutes(minutes).getSeconds();
    long nanos = d.minusHours(hours).minusMinutes(minutes).minusSeconds(seconds).toNanos();
    long micros = TimeUnit.NANOSECONDS.toMicros(nanos);

    if (micros != 0) {
        String origin = String.format("%02d:%02d:%02d.%06d", hours, minutes, seconds, micros);
        int length = origin.length();

        while (origin.charAt(length - 1) == '0') {
            --length;
        }

        return origin.substring(0, length);
    } else {
        return String.format("%02d:%02d:%02d", hours, minutes, seconds);
    }
}
 
Example 3
Source File: DurationCodecTest.java    From r2dbc-mysql with Apache License 2.0 6 votes vote down vote up
private static String format(Duration d) {
    long hours = d.toHours();
    long minutes = d.minusHours(hours).toMinutes();
    long seconds = d.minusHours(hours).minusMinutes(minutes).getSeconds();
    long nanos = d.minusHours(hours).minusMinutes(minutes).minusSeconds(seconds).toNanos();
    long micros = TimeUnit.NANOSECONDS.toMicros(nanos);

    if (micros != 0) {
        String origin = String.format("%02d:%02d:%02d.%06d", hours, minutes, seconds, micros);
        int length = origin.length();

        while (origin.charAt(length - 1) == '0') {
            --length;
        }

        return origin.substring(0, length);
    } else {
        return String.format("%02d:%02d:%02d", hours, minutes, seconds);
    }
}
 
Example 4
Source File: WebTemplateFunctions.java    From jweb-cms with GNU Affero General Public License v3.0 6 votes vote down vote up
public String fromNow(OffsetDateTime timestamp, String language) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM d", Locale.forLanguageTag(language));
    Duration duration = Duration.between(timestamp, OffsetDateTime.now());
    long seconds = duration.getSeconds();
    if (seconds <= 0) {
        return timestamp.format(formatter);
    }
    if (seconds - 60 < 0) {
        return String.format("1 %s", i18n("timeInterval.minuteBefore", language));
    }
    long minutes = duration.toMinutes();
    if (minutes - 60 < 0) {
        return String.format("%d %s", minutes, i18n("timeInterval.minutesBefore", language));
    }
    long hours = duration.toHours();
    if (hours - 2 < 0) {
        return String.format("1 %s", i18n("timeInterval.hourBefore", language));
    }
    if (hours - 24 < 0) {
        return String.format("%d %s", hours, i18n("timeInterval.hoursBefore", language));
    }
    return timestamp.format(formatter);
}
 
Example 5
Source File: JobRepresentation.java    From edison-microservice with Apache License 2.0 5 votes vote down vote up
private String formatRuntime(OffsetDateTime started, OffsetDateTime stopped) {
    Duration duration = Duration.between(started, stopped);

    if (duration.toHours() >= 24) {
        return "> 24h";
    }

    LocalTime dateTime = LocalTime.ofSecondOfDay(duration.getSeconds());
    return humanReadable
            ? ofPattern("HH:mm:ss").format(dateTime)
            : ofPattern("HH:mm:ss").format(dateTime);
}
 
Example 6
Source File: HumanDuration.java    From extract with MIT License 5 votes vote down vote up
/**
 * Convert the duration to a string of the same format that is accepted by {@link #parse(String)}.
 *
 * @return A formatted string representation of the duration.
 */
public static String format(final Duration duration) {
	long value = duration.toMillis();

	if (value >= 1000) {
		value = duration.getSeconds();
	} else {
		return String.format("%sms", value);
	}

	if (value >= 60) {
		value = duration.toMinutes();
	} else {
		return String.format("%ss", value);
	}

	if (value >= 60) {
		value = duration.toHours();
	} else {
		return String.format("%sm", value);
	}

	if (value >= 24) {
		value = duration.toDays();
	} else {
		return String.format("%sh", value);
	}

	return String.format("%sd", value);
}
 
Example 7
Source File: GlobalRepositorySettings.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
public void setLastDownloadedInterval(final Duration lastDownloadedInterval) {
  if (lastDownloadedInterval.toHours() < 1) {
    log.warn("A lastDownloaded interval of {} seconds has been configured, a value less than"
        + " 1 hour is not recommended for performance reasons", lastDownloadedInterval.getSeconds());
  }
  this.lastDownloadedInterval = lastDownloadedInterval;
}
 
Example 8
Source File: HoursRange.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
public int getDistanceInHours(LocalTime localTime) {
    if(includes(localTime)) {
        return 0;
    }
    Duration distanceFromStart = Duration.between(localTime, start);
    if(distanceFromStart.isNegative()) {
        return 24 + (int) distanceFromStart.toHours();
    }
    return (int) distanceFromStart.toHours();
}
 
Example 9
Source File: PostgreSQLIntervalType.java    From hibernate-types with Apache License 2.0 5 votes vote down vote up
@Override
protected void set(PreparedStatement st, Duration value, int index, SharedSessionContractImplementor session) throws SQLException {
    if (value == null) {
        st.setNull(index, Types.OTHER);
    } else {
        final int days = (int) value.toDays();
        final int hours = (int) (value.toHours() % 24);
        final int minutes = (int) (value.toMinutes() % 60);
        final double seconds = value.getSeconds() % 60;
        st.setObject(index, new PGInterval(0, 0, days, hours, minutes, seconds));
    }
}
 
Example 10
Source File: TimeWheel.java    From JavaBase with MIT License 5 votes vote down vote up
private boolean insertWheel(String id, Duration delay) {
  long days = delay.toDays();
  if (days > 30) {
    log.warn("out of timeWheel max delay bound");
    return false;
  }

  long current = System.currentTimeMillis();
  long delayMills = delay.toMillis();
  TaskNode node = new TaskNode(id, null, current, delayMills);
  if (days > 0) {
    return insertWheel(ChronoUnit.DAYS, this.currentDay.get() + days, node);
  }

  long hours = delay.toHours();
  if (hours > 0) {
    return insertWheel(ChronoUnit.HOURS, this.currentHour.get() + hours, node);
  }

  long minutes = delay.toMinutes();
  if (minutes > 0) {
    return insertWheel(ChronoUnit.MINUTES, this.currentMinute.get() + minutes, node);
  }

  long seconds = delay.getSeconds();
  // TODO expire too long time
  if (seconds >= -10 && seconds <= 1) {
    return insertWheel(ChronoUnit.SECONDS, this.currentSecond.get() + 1, node);
  }
  if (seconds > 1) {
    return insertWheel(ChronoUnit.SECONDS, this.currentSecond.get() + seconds, node);
  }

  log.warn("task is expire: id={} delay={}", id, delay);
  return false;
}
 
Example 11
Source File: StringFormatUtils.java    From datakernel with Apache License 2.0 5 votes vote down vote up
public static String formatDuration(Duration value) {
	if (value.isZero()) {
		return "0 seconds";
	}
	String result = "";
	long days, hours, minutes, seconds, nano, milli;
	days = value.toDays();
	if (days != 0) {
		result += days + " days ";
	}
	hours = value.toHours() - days * 24;
	if (hours != 0) {
		result += hours + " hours ";
	}
	minutes = value.toMinutes() - days * 1440 - hours * 60;
	if (minutes != 0) {
		result += minutes + " minutes ";
	}
	seconds = value.getSeconds() - days * 86400 - hours * 3600 - minutes * 60;
	if (seconds != 0) {
		result += seconds + " seconds ";
	}
	nano = value.getNano();
	milli = (nano - nano % 1000000) / 1000000;
	if (milli != 0) {
		result += milli + " millis ";
	}
	nano = nano % 1000000;
	if (nano != 0) {
		result += nano + " nanos ";
	}
	return result.trim();
}
 
Example 12
Source File: Time.java    From startup-os with Apache License 2.0 5 votes vote down vote up
public static String getHourMinuteDurationString(long timeMs) {
  Duration duration = Duration.of(timeMs, MILLIS);
  long hours = duration.toHours();
  long minutes = duration.minusHours(hours).toMinutes();
  if (hours == 0) {
    return String.format("%dmin", minutes);
  }
  return String.format("%dh %dmin", hours, minutes);
}
 
Example 13
Source File: DashboardController.java    From OEE-Designer with MIT License 5 votes vote down vote up
private double toDouble(Duration duration) {
	long value = 0;
	if (timeUnit.equals(Unit.SECOND)) {
		value = duration.getSeconds();
	} else if (timeUnit.equals(Unit.MINUTE)) {
		value = duration.toMinutes();
	} else if (timeUnit.equals(Unit.HOUR)) {
		value = duration.toHours();
	} else if (timeUnit.equals(Unit.DAY)) {
		value = duration.toDays();
	}
	return value;
}
 
Example 14
Source File: PeriodFormats.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
private static long periodAmount(TemporalUnit unit, Duration duration) {
  if (unit == ChronoUnit.DAYS) {
    return duration.toDays();
  } else if (unit == ChronoUnit.HOURS) {
    return duration.toHours();
  } else if (unit == ChronoUnit.MINUTES) {
    return duration.toMinutes();
  } else if (unit == ChronoUnit.SECONDS) {
    return duration.getSeconds();
  } else if (unit == ChronoUnit.MILLIS) {
    return duration.toMillis();
  } else {
    throw new IllegalArgumentException("Unsupported time unit: " + unit);
  }
}
 
Example 15
Source File: FrmSectionPlot.java    From MeteoInfo with GNU Lesser General Public License v3.0 5 votes vote down vote up
private List<String> getTimeGridStr() {
    List<String> GStrList = new ArrayList<>();
    int i;
    DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
    List<LocalDateTime> DTList = new ArrayList<>();
    for (i = 0; i < this.jComboBox_Time1.getItemCount(); i++) {
        DTList.add(LocalDateTime.parse(this.jComboBox_Time1.getItemAt(i).toString(), dateFormat));
    }

    String timeFormat;
    Duration duration = Duration.between(DTList.get(0), DTList.get(1));
    if (duration.getSeconds() < 3600) {
        timeFormat = "yyyy-MM-dd HH:mm";
    } else if (duration.toHours() < 24) {
        timeFormat = "yyyy-MM-dd HH";
    } else {
        timeFormat = "yyyy-MM-dd";
    }

    LocalDateTime ldt = DTList.get(0);
    int sYear = ldt.getYear();
    int sMonth = ldt.getDayOfMonth();
    ldt = DTList.get(DTList.size() - 1);
    int eYear = ldt.getYear();
    int eMonth = ldt.getDayOfMonth();
    if (sYear == eYear) {
        timeFormat = timeFormat.substring(5);
        if (sMonth == eMonth) {
            timeFormat = timeFormat.substring(3);
        }
    }

    DateTimeFormatter dataFormat = DateTimeFormatter.ofPattern(timeFormat);
    for (i = 0; i < DTList.size(); i++) {
        GStrList.add(dataFormat.format(DTList.get(i)));
    }

    return GStrList;
}
 
Example 16
Source File: DefaultAggregationService.java    From jetlinks-community with Apache License 2.0 5 votes vote down vote up
protected static String durationFormat(Duration duration) {
    String durationStr = duration.toString();
    if (durationStr.contains("S")) {
        return duration.toMillis() / 1000 + "s";
    } else if (!durationStr.contains("S") && durationStr.contains("M")) {
        return duration.toMinutes() + "m";
    } else if (!durationStr.contains("S") && !durationStr.contains("M")) {
        if (duration.toHours() % 24 == 0) {
            return duration.toDays() + "d";
        } else {
            return duration.toHours() + "h";
        }
    }
    throw new UnsupportedOperationException("不支持的时间周期:" + duration.toString());
}
 
Example 17
Source File: Utilities.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
public static String describeDuration(Duration d) {
  if (d.toDays() > 2) {
    return String.format("%s days", d.toDays());
  } else if (d.toHours() > 2) {
    return String.format("%s hours", d.toHours());
  } else if (d.toMinutes() > 2) {
    return String.format("%s mins", d.toMinutes());
  } else {
    return String.format("%s ms", d.toMillis());
  }
}
 
Example 18
Source File: DurationTest.java    From JavaBase with MIT License 4 votes vote down vote up
private String format(Duration duration) {
  return duration.toHours() + ":" + duration.toMinutes() + ":" + duration.getSeconds() % 60;
}
 
Example 19
Source File: JFRToFlameGraphWriter.java    From jfr-flame-graph with Apache License 2.0 4 votes vote down vote up
private void printJFRDetails(FlightRecording recording) {
    ITimeRange timeRange = recording.getTimeRange();

    long startTimestamp = TimeUnit.NANOSECONDS.toSeconds(timeRange.getStartTimestamp());
    long endTimestamp = TimeUnit.NANOSECONDS.toSeconds(timeRange.getEndTimestamp());

    Duration d = Duration.ofNanos(timeRange.getDuration());
    long hours = d.toHours();
    long minutes = d.minusHours(hours).toMinutes();

    IView view = recording.createView();

    long minEventStartTimestamp = Long.MAX_VALUE;
    long maxEventEndTimestamp = 0;

    view.setFilter(eventType::matches);

    for (IEvent event : view) {
        long eventStartTimestamp = event.getStartTimestamp();
        long eventEndTimestamp = event.getEndTimestamp();
        if (eventStartTimestamp < minEventStartTimestamp) {
            minEventStartTimestamp = eventStartTimestamp;
        }

        if (eventEndTimestamp > maxEventEndTimestamp) {
            maxEventEndTimestamp = eventEndTimestamp;
        }
    }

    Duration eventsDuration = Duration.ofNanos(maxEventEndTimestamp - minEventStartTimestamp);
    long eventHours = eventsDuration.toHours();
    long eventMinutes = eventsDuration.minusHours(eventHours).toMinutes();

    minEventStartTimestamp = TimeUnit.NANOSECONDS.toSeconds(minEventStartTimestamp);
    maxEventEndTimestamp = TimeUnit.NANOSECONDS.toSeconds(maxEventEndTimestamp);

    System.out.println("JFR Details");
    if (printTimestamp) {
        System.out.format(PRINT_FORMAT, "Start", startTimestamp);
        System.out.format(PRINT_FORMAT, "End", endTimestamp);
        System.out.format(PRINT_FORMAT, "Min Start Event", minEventStartTimestamp);
        System.out.format(PRINT_FORMAT, "Max End Event", maxEventEndTimestamp);
    } else {
        Instant startInstant = Instant.ofEpochSecond(startTimestamp);
        Instant endInstant = Instant.ofEpochSecond(endTimestamp);
        Instant minStartInstant = Instant.ofEpochSecond(minEventStartTimestamp);
        Instant maxEndInstant = Instant.ofEpochSecond(maxEventEndTimestamp);
        DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)
                .withZone(ZoneId.systemDefault());
        System.out.format(PRINT_FORMAT, "Start", formatter.format(startInstant));
        System.out.format(PRINT_FORMAT, "End", formatter.format(endInstant));
        System.out.format(PRINT_FORMAT, "Min Start Event", formatter.format(minStartInstant));
        System.out.format(PRINT_FORMAT, "Max End Event", formatter.format(maxEndInstant));
    }
    System.out.format(PRINT_FORMAT, "JFR Duration", MessageFormat.format(DURATION_FORMAT, hours, minutes));
    System.out.format(PRINT_FORMAT, "Events Duration",
            MessageFormat.format(DURATION_FORMAT, eventHours, eventMinutes));
}
 
Example 20
Source File: DurationTool.java    From axelor-open-suite with GNU Affero General Public License v3.0 4 votes vote down vote up
public static long getHoursDuration(Duration duration) {
  return duration.toHours();
}