Java 减去本地时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28353725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 06:05:19  来源:igfitidea点击:

Java subtract LocalTime

javalocaltime

提问by Bob

I have two LocalTimeobjects:

我有两个LocalTime对象:

LocalTime l1 = LocalTime.parse("02:53:40");
LocalTime l2 = LocalTime.parse("02:54:27");

How can I found different in minutes between them?

我怎么能在几分钟内发现它们之间的不同?

采纳答案by Yosef Weiner

Use untilor between, as described by the api

使用untilor between,如api 所述

import java.time.LocalTime;
import static java.time.temporal.ChronoUnit.MINUTES;

public class SO {
    public static void main(String[] args) {
        LocalTime l1 = LocalTime.parse("02:53:40");
        LocalTime l2 = LocalTime.parse("02:54:27");
        System.out.println(l1.until(l2, MINUTES));
        System.out.println(MINUTES.between(l1, l2));
    }
}

0
0

0
0

回答by Lev Kuznetsov

You could do this:

你可以这样做:

long dif = Math.abs (l1.getLocalMillis () - l2.getLocalMillis ());
TimeUnit.MINUTES.convert (dif, TimeUnit.MILLISECONDS);

回答by Neeraj Jain

I do this withChronoUnit

我用ChronoUnit做这个

long minutesBetween = ChronoUnit.MINUTES.between(l1,l2);

Example

例子

    LocalTime localTime=LocalTime.now();
    LocalTime localTimeAfter5Minutes=LocalTime.now().plusMinutes(5);
    Long minutesBetween=ChronoUnit.MINUTES.between(localTime,localTimeAfter5Minutes);
    System.out.println("Diffrence between time in munutes : "+minutesBetween);

Output

输出

Diffrence between time in munutes : 5

回答by nslxndr

Since Java 8 you can use Durationclass. I think that gives the most elegant solution:

从 Java 8 开始,您可以使用Duration类。我认为这给出了最优雅的解决方案:

long elapsedMinutes = Duration.between(l1, l2).toMinutes();