使用Java 8 java.time进行时间计算。*

时间:2016-02-08 15:52:47

标签: java java-time

让我们//our root app component import {Component, EventEmitter} from 'angular2/core' class Item { name: boolean; constructor(name: string) { this.name = name; } } @Component({ selector: 'my-item', template: ` <div> <label><input type="checkbox" [(ngModel)]="state"/> {{state}}</label> </div> ` }) export class MyItemComponent { state: boolean = false; } @Component({ selector: 'my-app', template: ` <div style="border: 1px solid red;"> <label><input type="checkbox" [(ngModel)]="state"/> {{state}}</label> </div> <div *ngFor="#item of items"> <my-item></my-item> </div> `, directives: [MyItemComponent] }) export class App { state: boolean = true; items: Item[] = []; constructor() { this.items.push(new Item("hello")); this.items.push(new Item("test")); } } - 某个事件的起点和java.time.Instant - 此事件的持续时间。

我可以使用java.time.Duration来计算另一个java.time.Period是否属于这个时期吗?如果不是 - 我应该使用哪种方法来定义它?

4 个答案:

答案 0 :(得分:3)

ThreeTen-Extra项目包含java.time个功能,这些功能并没有为JDK做好准备。其中一个是Interval,请参阅Javadoc

使用Interval,此问题可写为:

Interval iv = Interval.of(start, duration);
boolean contains = iv.contains(instantToCheck);

答案 1 :(得分:1)

鉴于即时instant和持续时间duration,您需要检查即时toCheck是否属于[instant; instant + duration]区间。

为此,您可以使用Duration.between计算instanttoCheck之间的持续时间。如果此持续时间为正且小于指定的持续时间,则要检查的时间是在所需的时间间隔内。

public static void main(String[] args) {
    Instant instant = Instant.now();
    Duration duration = Duration.ofSeconds(10);
    Instant toCheck = instant.plusSeconds(5);

    Duration d = Duration.between(instant, toCheck);
    if (!d.isNegative() && d.compareTo(duration) <= 0) {
        System.out.println("is in interval!");
    }
}

答案 2 :(得分:1)

基于开始和结束Instant的另一种解决方案,用于更直观的比较:

    Instant start     = Instant.now(); // your value
    Duration duration = Duration.ofSeconds(10);  // your value
    Instant end       = start.plus(duration);

    Instant toCheck   = start.plusSeconds(5); // your value
    if (!toCheck.isBefore(start) && !toCheck.isAfter(end)) 
        System.out.println("is in interval!");

答案 3 :(得分:1)

根据OP的要求使用Period的更加扭曲的示例。如果您想在您的Instants之间使用DaysWeeksMonths等,并且希望确保无缝地处理夏令时,闰年等,这会更有用。< / p>

Instant start = Instant.now();
ZonedDateTime eventStart = ZonedDateTime.ofInstant(start, ZoneId.systemDefault());
ZonedDateTime eventEnd = eventStart.plus(Period.ofDays(5));
Instant end = eventEnd.toInstant();

Instant toCheck = start.plus(2, ChronoUnit.DAYS);

if (!toCheck.isBefore(start) && !toCheck.isAfter(end))
{
  System.out.println("Instant to check is between start and end");
}