[英]How to get the difference between two Dates in minutes in Java
我有一个如下所示的日期列表:
I/System.out: TAG: Mon Jun 20 15:36:00 GMT+02:00 2022
I/System.out: TAG: Mon Jun 20 15:51:55 GMT+02:00 2022
I/System.out: TAG: Mon Jun 20 15:52:14 GMT+02:00 2022
I/System.out: TAG: Mon Jun 20 16:24:01 GMT+02:00 2022
I/System.out: TAG: Mon Jun 20 18:39:07 GMT+02:00 2022
I/System.out: TAG: Mon Jun 20 18:49:02 GMT+02:00 2022
I/System.out: TAG: Mon Jun 20 20:24:26 GMT+02:00 2022
I/System.out: TAG: Mon Jun 20 20:52:23 GMT+02:00 2022
I/System.out: TAG: Mon Jun 20 22:41:50 GMT+02:00 2022
I/System.out: TAG: Mon Jun 20 22:55:54 GMT+02:00 2022
如何计算从 i 元素中减去每个 i+1 元素(例如:标签:2022 年 6 月 20 日星期一 15:51:55 GMT+02:00 2022 年 - 标签:2022 年 6 月 20 日星期一 15:36:00 GMT+02:00 2022) 相差 21 分钟。
我尝试了这样的事情:
for(int i=0;i<list.size()-1;i++){
parked += list.get(i+1).getTime() - list.get(i).getTime();
}
System.out.println("parked time: "+parked / 60 000);
我得到 434 分钟而不是 98 分钟......有人可以帮忙吗? 致谢
通过查看您的问题,我发现了能够解决您问题的其他帖子。 作为解决方案提供的代码能够将 Date 转换为简单的可读值。
/**
* Get a diff between two dates
* @param date1 the oldest date
* @param date2 the newest date
* @param timeUnit the unit in which you want the diff
* @return the diff value, in the provided unit
*/
public static long getDateDiff(Date date1, Date date2, TimeUnit timeUnit) {
long diffInMillies = date2.getTime() - date1.getTime();
return timeUnit.convert(diffInMillies,TimeUnit.MILLISECONDS);
}
然后你需要打电话来获取你的价值
getDateDiff(date1,date2,TimeUnit.MINUTES);
尝试这个
public double findDifference(String start_date, String end_date)
{
// SimpleDateFormat converts the
// string format to date object
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
double diff = 0;
// Try Block
try {
// parse method is used to parse
// the text from a string to
// produce the date
Date d1 = sdf.parse(start_date);
Date d2 = sdf.parse(end_date);
// Calucalte time difference
// in milliseconds
long difference_In_Time = d2.getTime() - d1.getTime();
// Calucalte time difference in
// seconds, minutes, hours, years,
// and days
long difference_In_Seconds = (difference_In_Time / 1000) % 60;
long difference_In_Minutes = (difference_In_Time / (1000 * 60)) % 60;
long day = (difference_In_Time / (1000 * 60 * 60)) % 24;
long difference_In_Years = (difference_In_Time / (1000L * 60 * 60 * 24 * 365));
long difference_In_Days = (difference_In_Time / (1000 * 60 * 60 * 24)) % 365;
// Print the date difference in
// years, in days, in hours, in
// minutes, and in seconds
}
// Catch the Exception
catch (ParseException e) {
e.printStackTrace();
}
return diff;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.