0
private double calculateAverageSpeed() {
    SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss", Locale.ENGLISH);

    try {
        double totalTime;
        totalTime = (format.parse(stopTime + ":00").getTime()) - (format.parse(startTime + ":00").getTime());
        return (milesDriven / totalTime);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return 0;
}
Dmitry Kuzminov
  • 6,180
  • 6
  • 18
  • 40
userSB
  • 1
  • 1
  • can you share the format , how you are passing the date to this method – maddy Jun 29 '20 at 23:31
  • Trip one 12:01 13:16 42.0 Trip two 07:15 07:45 17.3 Trip three 06:12 06:32 21.8 – userSB Jun 29 '20 at 23:37
  • I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalTime` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Jun 30 '20 at 19:57

2 Answers2

0

You're parsing strings that look like 24-hour-clock times with a format specifier that wants 12-hour times with AM/PM indicators (hh:mm:ss).

My guess is that "12:01" is interpreted as one minute after midnight. Use HH:mm:ss for 24-hour times.

user13784117
  • 1,124
  • 4
  • 4
0

I hope this might help you
Also you can use time format "HH:mm" for 24 hour format , I have used "hh:mm"

if you use "HH:mm"

you will get result like this

Time: Thu Jan 01 12:01:00 PST 1970 72060000
Time: Thu Jan 01 13:16:00 PST 1970 76560000
diff==4500000
totalTime=1
42.0

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class TimeDifference {

public static void main(String[] args) throws ParseException {

  System.out.println(calculateAverageSpeed("12:01","13:16",42.0));
 

}

 private static double calculateAverageSpeed(String time1,String time2, double 
 miles) throws ParseException { 

DecimalFormat decimalFormatter = new DecimalFormat("###,###");
 

SimpleDateFormat format = new SimpleDateFormat("hh:mm", Locale.ENGLISH);
Date date = format.parse(time1);
Date date2 = format.parse(time2);

System.out.println("Time: " + date+ " "+date.getTime());
System.out.println("Time: " + date2+ " "+date2.getTime());
long diff = date2.getTime() - date.getTime();
System.out.println("diff=="+diff); 
int totalTime = (int)(diff/(60*60*1000));
System.out.println("totalTime="+decimalFormatter.format(totalTime));

return  (miles / totalTime);
}


}

you will get kind of this result . Time: Thu Jan 01 00:01:00 PST 1970 28860000
Time: Thu Jan 01 13:16:00 PST 1970 76560000
diff==47700000
totalTime=13
3.230769230769231

maddy
  • 129
  • 1
  • 4