java.time:比较两个 Instant - 获取两者之间的小时数、分钟数、秒数、年数、月数

par*_*cer 1 java datetime unix-timestamp

我尝试了这段代码:

public class TimePassed {
    private long seconds;
    private long minutes;
    private long hours;
    private long days;
    private long years;
    ...

    public TimePassed(double unixSeconds)  {
        Instant now = Instant.now();
        Instant ago = Instant.ofEpochSecond((long) unixSeconds);

        this.seconds = ChronoUnit.SECONDS.between(
            ago.atZone(ZoneId.systemDefault()),
            now.atZone(ZoneId.systemDefault()));  //6100
        this.minutes = ChronoUnit.MINUTES.between(
            ago.atZone(ZoneId.systemDefault()),
            now.atZone(ZoneId.systemDefault()));  //101
        this.hours = ChronoUnit.HOURS.between(
            ago.atZone(ZoneId.systemDefault()),
            now.atZone(ZoneId.systemDefault()));  //1
        this.days = ChronoUnit.DAYS.between(
            ago.atZone(ZoneId.systemDefault()),
            now.atZone(ZoneId.systemDefault()));  //0
        this.years = ChronoUnit.YEARS.between(
            ago.atZone(ZoneId.systemDefault()),
            now.atZone(ZoneId.systemDefault()));  //0
    }
}
Run Code Online (Sandbox Code Playgroud)

然而,那么该TimePassed对象将具有seconds = 6100和,而我希望它是minutes = 101, ,所以。可以做包吗?因为到目前为止,我只能得到过去的秒数、过去的分钟或过去的小时等等。而且两者都无法解释对方。hours = 1hours = 1minutes = 41, seconds = 4060*60 + 41*60 + 40 = 6100java.time

Ole*_*.V. 5

Java 9 答案:Duration.toXxxPart 方法

\n\n

基本想法,不完整:

\n\n
    Duration dur = Duration.between(ago, now);\n\n    this.seconds = dur.toSecondsPart(); // 40\n    this.minutes = dur.toMinutesPart(); // 41\n    this.hours = dur.toHoursPart(); // 1\n    this.days = dur.toDaysPart(); // 0\n
Run Code Online (Sandbox Code Playgroud)\n\n

使用与问题相隔 6100 秒的时刻进行测试。这些toXxxPart方法是在 Java 9 中引入的。对于 Java 8(或 ThreeTen Backport),您需要从较粗的单位(天)开始,并从持续时间中减去它们,然后再获得下一个更精细的单位。请参阅lauhub 的回答作为示例

\n\n

不过,要完全正确地计算年份和日期有点困难。要仅获取超过整年的天数,请在此处\xe2\x80\x99s 获取完整代码:

\n\n
    ZoneId zone = ZoneId.systemDefault();\n    ZonedDateTime agoZdt = ago.atZone(zone);\n    ZonedDateTime nowZdt = now.atZone(zone);\n    this.years = ChronoUnit.YEARS.between(agoZdt, nowZdt);\n    ZonedDateTime afterWholeYears = agoZdt.plusYears(this.years);\n\n    Duration dur = Duration.between(afterWholeYears, nowZdt);\n\n    this.seconds = dur.toSecondsPart(); // 40\n    this.minutes = dur.toMinutesPart(); // 41\n    this.hours = dur.toHoursPart(); // 1\n    this.days = dur.toDays(); // 0\n
Run Code Online (Sandbox Code Playgroud)\n\n

我故意ZoneId.systemDefault()只阅读一次,只是为了防止有人更改正在进行的默认时区设置。

\n