当前位置: 首页>>代码示例>>Java>>正文


Java Duration.between方法代码示例

本文整理汇总了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;
}
 
开发者ID:powsybl,项目名称:powsybl-core,代码行数:20,代码来源:TimeSeries.java

示例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;
}
 
开发者ID:mrluo735,项目名称:cas-5.1.0,代码行数:19,代码来源:StatisticsController.java

示例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());
}
 
开发者ID:OvercastNetwork,项目名称:ProjectAres,代码行数:13,代码来源:Match.java

示例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());
    }
 
开发者ID:juebanlin,项目名称:util4j,代码行数:14,代码来源:TimeIntroduction.java

示例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);
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:9,代码来源:TCKDuration.java

示例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();
}
 
开发者ID:VoxelGamesLib,项目名称:VoxelGamesLibv2,代码行数:38,代码来源:AbstractPhase.java

示例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)"));
    });
}
 
开发者ID:killjoy1221,项目名称:WhoIs,代码行数:38,代码来源:Whois.java

示例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);

}
 
开发者ID:gchq,项目名称:stroom-stats,代码行数:30,代码来源:TestCountStatToAggregateFlatMapper.java

示例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());
}
 
开发者ID:OvercastNetwork,项目名称:ProjectAres,代码行数:12,代码来源:Match.java

示例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 () ) );
    }
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:9,代码来源:StoppingTest.java

示例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));
    }
}
 
开发者ID:PacktPublishing,项目名称:Java-9-Programming-Blueprints,代码行数:40,代码来源:DupeFinderCommands.java

示例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);
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:7,代码来源:TCKDuration.java

示例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);
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:6,代码来源:TCKDuration.java

示例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);

}
 
开发者ID:after-the-sunrise,项目名称:cryptotrader,代码行数:23,代码来源:LastEstimator.java

示例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;
    }
}
 
开发者ID:Panzer1119,项目名称:JAddOn,代码行数:44,代码来源:ArrayListUtils.java


注:本文中的java.time.Duration.between方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。