两个日期之差

时间:2018-07-30 06:18:13

标签: java date

我需要得到以下2个日期之间的差额。这两个日期均为字符串格式。

.libs/libbat_la-gdk_select.o:gdk_select.c:(.text+0x19f4c0): first defined here
collect2: error: ld returned 1 exit status
make[3]: *** [libbat.la] Error 1
make[3]: Leaving directory `/<FULL PATH>/MonetDB_temp/gdk'
make[2]: *** [all] Error 2
make[2]: Leaving directory `/<FULL PATH/MonetDB_temp/gdk'
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory `/<FULL PATH>/MonetDB_temp'
make: *** [all] Error 2

2 个答案:

答案 0 :(得分:1)

引号

您忘记了输入字符串周围的双引号。

java.time

您正在使用 java.time 类在几年前过时的可怕旧类。

解析

使用DateTimeFormatter解析输入字符串以获取ZonedDateTime对象。搜索堆栈溢出,因为已经讨论了很多次。

已用

要计算经过的小时,分​​钟和秒,请将那些ZonedDateTime对象传递给Duration.between方法。对于年月日,请使用Period。搜索堆栈溢出,因为已经讨论了很多次。

答案 1 :(得分:0)

尝试一下:-

String sDate1 = Thu Jun 26 13:45:32 IST 2018;
String sDate2 = Thu Jul 16 03:25:37 IST 2018;

Date d1= new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy").parse(sDate1);
Date d2= new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy").parse(sDate2); 
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000);
System.out.println("Time in seconds: " + diffSeconds + " seconds.");
System.out.println("Time in minutes: " + diffMinutes + " minutes.");
System.out.println("Time in hours: " + diffHours + " hours.");

或者您可以使用TimeUnit:-

long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(diff );
long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(diff );
long diffInHours = TimeUnit.MILLISECONDS.toHours(diff );