本文整理汇总了Java中java.time.Duration.between方法的典型用法代码示例。如果您正苦于以下问题:Java Duration.between方法的具体用法?Java Duration.between怎么用?Java Duration.between使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.time.Duration
的用法示例。
在下文中一共展示了Duration.between方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: checkRegularSpacing
import java.time.Duration; //导入方法依赖的package包/类
private Duration checkRegularSpacing() {
if (times.size() < 2) {
throw new TimeSeriesException("At least 2 rows are expected");
}
Duration spacing = null;
for (int i = 1; i < times.size(); i++) {
Duration duration = Duration.between(times.get(i - 1), times.get(i));
if (spacing == null) {
spacing = duration;
} else {
if (!duration.equals(spacing)) {
throw new TimeSeriesException("Time spacing has to be regular");
}
}
}
return spacing;
}
示例2: getAvailability
import java.time.Duration; //导入方法依赖的package包/类
/**
* Gets availability times of the server.
*
* @param request the http servlet request
* @param response the http servlet response
* @return the availability
*/
@GetMapping(value = "/getAvailability")
@ResponseBody
public Map<String, Object> getAvailability(final HttpServletRequest request,
final HttpServletResponse response) {
ensureEndpointAccessIsAuthorized(request, response);
final Map<String, Object> model = new HashMap<>();
final Duration diff = Duration.between(this.upTimeStartDate, ZonedDateTime.now(ZoneOffset.UTC));
model.put("upTime", diff.getSeconds());
return model;
}
示例3: getLength
import java.time.Duration; //导入方法依赖的package包/类
/**
* If the match has not started, throws {@link IllegalStateException}
* If the match is running, return the time since it started.
* If the match is finished, return the total time it ran for.
*/
default Duration getLength() {
Instant startTime = getStateChangeTime(MatchState.Running);
if(startTime == null) {
throw new IllegalStateException("match has not started yet");
}
return Duration.between(startTime, getEndTime());
}
示例4: testDuration
import java.time.Duration; //导入方法依赖的package包/类
public static void testDuration() {
//表示两个瞬时时间的时间段
Duration d1 = Duration.between(Instant.ofEpochMilli(System.currentTimeMillis() - 12323123), Instant.now());
//得到相应的时差
System.out.println(d1.toDays());
System.out.println(d1.toHours());
System.out.println(d1.toMinutes());
System.out.println(d1.toMillis());
System.out.println(d1.toNanos());
//1天时差 类似的还有如ofHours()
Duration d2 = Duration.ofDays(1);
System.out.println(d2.toDays());
}
示例5: factory_between_TemporalTemporal_Instant
import java.time.Duration; //导入方法依赖的package包/类
@Test(dataProvider="durationBetweenInstant")
public void factory_between_TemporalTemporal_Instant(long secs1, int nanos1, long secs2, int nanos2, long expectedSeconds, int expectedNanoOfSecond) {
Instant start = Instant.ofEpochSecond(secs1, nanos1);
Instant end = Instant.ofEpochSecond(secs2, nanos2);
Duration t = Duration.between(start, end);
assertEquals(t.getSeconds(), expectedSeconds);
assertEquals(t.getNano(), expectedNanoOfSecond);
}
示例6: stop
import java.time.Duration; //导入方法依赖的package包/类
@Override
public void stop() {
// stop timer
duration = Duration.between(startTime, LocalDateTime.now());
log.finer("stop phase " + getName());
// only stop features that have been started to avoid errors
for (Feature feature : startedFeatures) {
log.finer("stop " + feature.getName());
try {
feature.stop();
} catch (Exception ex) {
log.severe("error while stopping " + feature.getName());
ex.printStackTrace();
return;
}
if (feature instanceof Listener) {
eventHandler.unregister((Listener) feature, getGame());
}
if (feature instanceof FeatureCommandImplementor) {
AbstractFeatureCommand cmd = injector.getInstance(((FeatureCommandImplementor) feature).getCommandClass());
commandHandler.unregister(cmd, this);
}
}
phaseTickables.values().forEach(tickable -> {
tickable.stop();
if (tickable instanceof Ability) {
((Ability) tickable).unregister();
}
});
startedFeatures.clear();
}
示例7: timeSince
import java.time.Duration; //导入方法依赖的package包/类
private static Function<Instant, Text> timeSince(final Locale locale) {
return (instant -> {
Text text = Text.of(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
.withLocale(locale)
.withZone(ZoneId.systemDefault())
.format(instant));
String str = instant.compareTo(Instant.now()) < 0 ? " (%s %s from now)" : " (%s %s ago)";
Duration dur = Duration.between(instant, Instant.now());
if (dur.getSeconds() < 1)
return text.concat(Text.of(" (Now)"));
// seconds
if (dur.getSeconds() < 60)
return text.concat(Text.of(String.format(str, dur.getSeconds(), "seconds")));
// minutes
if (dur.toMinutes() < 60)
return text.concat(Text.of(" (" + dur.toMinutes() + " minutes ago)"));
// hours
if (dur.toHours() < 24)
return text.concat(Text.of(" (" + dur.toHours() + " hours ago)"));
// days
if (dur.toDays() < 365)
return text.concat(Text.of(" (" + dur.toDays() + " days ago)"));
// Duration doesn't support months or years
Period per = Period.between(LocalDate.from(instant), LocalDate.now());
// months
if (per.getMonths() < 12) {
return text.concat(Text.of(" (" + per.getMonths() + " months ago)"));
}
// years
return text.concat(Text.of(" (" + per.getYears() + " years ago)"));
});
}
示例8: flatMap_AllRollUps_noTags
import java.time.Duration; //导入方法依赖的package包/类
@Test
public void flatMap_AllRollUps_noTags() throws Exception {
Statistics.Statistic statistic = buildStatisticNoTags();
StatisticConfiguration statisticConfiguration = new MockStatisticConfiguration()
.setUuid(statUuid)
.setName(statName)
.setStatisticType(StatisticType.COUNT)
.setRollUpType(StatisticRollUpType.ALL)
.addFieldNames(tag1, tag2)
.setPrecision(EventStoreTimeIntervalEnum.SECOND);
mockStatisticConfigurationService.addStatisticConfiguration(statisticConfiguration);
StatisticWrapper statisticWrapper = new StatisticWrapper(statistic, Optional.of(statisticConfiguration));
Instant start = Instant.now();
Iterable<KeyValue<StatEventKey, StatAggregate>> iterable = countStatToAggregateMapper.flatMap(statUuid, statisticWrapper);
Duration executionTime = Duration.between(start, Instant.now());
LOGGER.debug("Execution time: {}ms", executionTime.toMillis());
List<KeyValue<StatEventKey, StatAggregate>> keyValues = (List<KeyValue<StatEventKey, StatAggregate>>) iterable;
//no tags so nothing to rollup, thus just get the original event
assertThat(keyValues).hasSize(1);
}
示例9: runningTime
import java.time.Duration; //导入方法依赖的package包/类
/**
* Get the duration of the match, or zero if the match has not started
*/
@Override
default Duration runningTime() {
Instant startTime = getStateChangeTime(MatchState.Running);
if(startTime == null) {
return Duration.ZERO;
}
return Duration.between(startTime, getEndTime());
}
示例10: assertMax
import java.time.Duration; //导入方法依赖的package包/类
private void assertMax ( final Instant start, final int wait )
{
final Duration duration = Duration.between ( start, now () );
if ( duration.toMillis () > wait )
{
fail ( String.format ( "Should take less than %s ms, took %s ms", wait, duration.toMillis () ) );
}
}
示例11: findDupes
import java.time.Duration; //导入方法依赖的package包/类
@Command
public void findDupes(@Option("pattern") List<String> patterns,
@Option("path") List<String> paths,
@Option("verbose") @Default("false") boolean verbose,
@Option("show-timings") @Default("false") boolean showTimings) {
if (verbose) {
System.out.println("Scanning for duplicate files.");
System.out.println("Search paths:");
paths.forEach(p -> System.out.println("\t" + p));
System.out.println("Search patterns:");
patterns.forEach(p -> System.out.println("\t" + p));
System.out.println();
}
final Instant startTime = Instant.now();
FileFinder ff = new FileFinder();
patterns.forEach(p -> ff.addPattern(p));
paths.forEach(p -> ff.addPath(p));
ff.find();
System.out.println("The following duplicates have been found:");
java.math.BigInteger b;
final AtomicInteger group = new AtomicInteger(1);
ff.getDuplicates().forEach((name, list) -> {
System.out.printf("Group #%d:%n", group.getAndIncrement());
list.forEach(fileInfo -> System.out.println("\t" + fileInfo.getPath()));
});
final Instant endTime = Instant.now();
if (showTimings) {
Duration duration = Duration.between(startTime, endTime);
long hours = duration.toHours();
long minutes = duration.minusHours(hours).toMinutes();
long seconds = duration.minusHours(hours).minusMinutes(minutes).toMillis() / 1000;
System.out.println(String.format("%nThe scan took %d hours, %d minutes, and %d seconds.%n", hours, minutes, seconds));
}
}
示例12: factory_between_TemporalTemporal_invalidMixedTypes
import java.time.Duration; //导入方法依赖的package包/类
@Test(expectedExceptions=DateTimeException.class)
public void factory_between_TemporalTemporal_invalidMixedTypes() {
Instant start = Instant.ofEpochSecond(1);
LocalDate end = LocalDate.of(2010, 6, 20);
Duration.between(start, end);
}
示例13: factory_between__TemporalTemporal_startNull
import java.time.Duration; //导入方法依赖的package包/类
@Test(expectedExceptions=NullPointerException.class)
public void factory_between__TemporalTemporal_startNull() {
Instant end = Instant.ofEpochSecond(1);
Duration.between(null, end);
}
示例14: calculateConfidence
import java.time.Duration; //导入方法依赖的package包/类
@VisibleForTesting
BigDecimal calculateConfidence(Instant time, Instant now) {
Duration duration = Duration.between(time, now);
if (duration.isZero() || duration.isNegative()) {
return ONE;
}
// Number from 0 to 29 (= 100 years)
double scaled = Math.log(duration.toMillis());
// Number from 0.00 to 0.79
double multiplied = scaled * Math.E / 100;
// Number from 100.00 to 0.21
double confidence = 1 - multiplied;
// Sanitize in case if +3000 years...
return BigDecimal.valueOf(confidence).max(ZERO).setScale(SCALE, HALF_UP);
}
示例15: contains
import java.time.Duration; //导入方法依赖的package包/类
public static ArrayListPosition contains(final ArrayList<?> arraylist, final Object object, final int threadPoolSize) {
final Instant instant_start = Instant.now();
final ExecutorService executor = Executors.newFixedThreadPool(threadPoolSize);
final ArrayListPosition alp = new ArrayListPosition();
if(arraylist.size() >= threadPoolSize && arraylist.size() >= MINARRAYLISTSIZE) {
final int steps = arraylist.size() / threadPoolSize;
for(int i = 0; i < threadPoolSize; i++) {
final int u = i;
Runnable run = new Runnable() {
@Override
public void run() {
final int extra = ((u == threadPoolSize - 1) ? (steps * threadPoolSize) - arraylist.size() : 0);
for(int z = 0; z < steps + extra; z++) {
if(arraylist.get(u * steps + z).equals(object)) {
final Instant instant_stop = Instant.now();
final Duration duration = Duration.between(instant_start, instant_stop);
alp.setContains(true);
alp.setObject(object);
alp.setPosition((u * steps + z));
alp.setDuration(duration);
executor.shutdownNow();
}
//StaticStandard.log(String.format("[%s] Step: %d, Overall: %d, Percentage: %.2f", Thread.currentThread().getName(), z, (u * steps + z), ((z * 1.0) / (steps * 1.0) * 100.0)));
}
}
};
executor.execute(run);
}
executor.shutdown();
try {
executor.awaitTermination(1, TimeUnit.DAYS);
} catch (Exception ex) {
}
return alp;
} else {
alp.setContains(arraylist.contains(object));
alp.setObject(alp.isContains() ? object : null);
alp.setPosition(alp.isContains() ? arraylist.indexOf(object) : -1);
return alp;
}
}