我正在尝试像下面这样在两个小时之间取得差异

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更改。

10-06 13:29