gpt4 book ai didi

java - 如何在java中从两次获取分钟

转载 作者:行者123 更新时间:2023-11-29 03:09:22 25 4
gpt4 key购买 nike

我正在尝试像下面这样计算两个小时之间的差异

String time1 = "05:00 AM";
String time2 = "06:20 AM";

String format = "HH:mm aa";

SimpleDateFormat sdf = new SimpleDateFormat ( format );

Date dateObj1 = null;
Date dateObj2 = null;
try {
dateObj1 = sdf.parse ( time1 );
dateObj2 = sdf.parse ( time2 );
} catch ( ParseException e ) {
e.printStackTrace ( );
}

long diff = dateObj2.getTime ( ) - dateObj1.getTime ( );
double diffInHours = diff / ( ( double ) 1000 * 60 * 60 );
double diffInMins = ( diffInHours + ( int ) diffInHours ) * 60;

转储到控制台。

System.out.println ( "diff: " + diff );
System.out.println ( "diffInHours: " + diffInHours );
System.out.println ( "diffInMins " + diffInMins );

运行时。

diffInHours 1.3333333333333333
Minutes 139.99999999999997

我想计算两次之间的时间(以分钟为单位),就像在上面的例子中我应该得到 80 分钟,但它给出了一些其他值。

有人能帮我算出两次之间的分钟数吗?

最佳答案

对于 Java 8,它可能看起来像这样:

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("hh:mm a");
LocalTime t1 = LocalTime.parse(time1, fmt);
LocalTime t2 = LocalTime.parse(time2, fmt);
long minutes = ChronoUnit.MINUTES.between(t1, t2); //80

请注意,这不会考虑任何 DST 更改。

关于java - 如何在java中从两次获取分钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30257375/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com