I have a list of Dates that looks like this:
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
How do I calculate to subtract each i 1 element from the i element(example: TAG: Mon Jun 20 15:51:55 GMT 02:00 2022 - TAG: Mon Jun 20 15:36:00 GMT 02:00 2022) difference is 21 minutes.
I tryed something like this:
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);
and I get 434 minutes instead of 98... Can someone help? Thanks in regards
CodePudding user response:
By looking at your question i found this other post that is able to solve your issue. The code presented as solution is able to convert Date to simple readable values.
Calculating the difference between two Java date instances
/**
* 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);
}
Then you need to call to obtain your value
getDateDiff(date1,date2,TimeUnit.MINUTES);
CodePudding user response:
Try this
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;
}