Java 两次之间的差异(以分钟为单位)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18686575/
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-12 10:10:20  来源:igfitidea点击:

Difference between two times in minutes

javatime

提问by user2704743

I've seen some examples using Joda Time and other methods to work out the difference between two dates in milliseconds, but how can these be applied to just get the difference between two times in minutes? For example, the difference between 2:45pm and 11:00am is 225 minutes.

我已经看到一些示例使用 Joda Time 和其他方法来计算两个日期之间的差异(以毫秒为单位),但是如何应用这些方法来获得两次时间之间的差异(以分钟为单位)?例如,下午 2:45 和上午 11:00 之间的差异是 225 分钟。

采纳答案by dasblinkenlight

You can work out the math by observing that one minute is sixty seconds, one second is one thousand milliseconds, so one minute is 60*1000milliseconds.

你可以通过观察一分钟是六十秒,一秒是一千毫秒,所以一分钟是60*1000毫秒来算出数学。

If you divide milliseconds by 60,000, seconds will be truncated. You should divide the number by 1000 to truncate milliseconds, then take n % 60as the number of seconds and n / 60as the number of minutes:

如果将毫秒除以 60,000,秒将被截断。您应该将数字除以 1000 以截断毫秒,然后n % 60作为秒数和n / 60分钟数:

Date d1 = ...
Date d2 = ...
long diffMs = d1.getTime() - d2.getTime();
long diffSec = diffMs / 1000;
long min = diffSec / 60;
long sec = diffSec % 60;
System.out.println("The difference is "+min+" minutes and "+sec+" seconds.");

回答by NPE

To convert milliseconds to minutes, divide by 60000.

要将毫秒转换为分钟,请除以60000

回答by Sotirios Delimanolis

With JodaTime, you can do the following to get exact minutes

使用JodaTime,您可以执行以下操作以获取准确的分钟数

public static void main(String[] args) throws Exception {   //Read user input into the array
    long time = System.currentTimeMillis(); // current time
    DateTime time1 = new DateTime(time);
    DateTime time2 = new DateTime(time + 120_000); // add 2 minutes for example
    Minutes minutes = Minutes.minutesBetween(time1, time2);
    System.out.println(minutes.getMinutes()); // prints 2
}

The Minutes.minutesBetween()accepts a ReadableInstantparameter which isn't necessarily a DateTimeobject.

Minutes.minutesBetween()接受一个ReadableInstant参数,其不一定是一个DateTime对象。