Java - Time difference in minutes

java

Solution

This is not working because when you create a new date with just a time in it, it's assuming the day is "today".

What you could do is:

// This example works
String dateStart = "2045";
String dateStop = "2300";

// This example doesnt work
//String dateStart = "2330";
//String dateStop = "0245";

// Custom date format
SimpleDateFormat format = new SimpleDateFormat("HHmm");  

Date d1 = null;
Date d2 = null;
try {
    d1 = format.parse(dateStart);
    d2 = format.parse(dateStop);
} catch (Exception e) {
    e.printStackTrace();
}

// MY ADDITION TO YOUR CODE STARTS HERE
if(d2.before(d1)){
    Calendar c = Calendar.getInstance(); 
    c.setTime(d2); 
    c.add(Calendar.DATE, 1);
    d2 = c.getTime();
}
// ENDS HERE

long diff = d2.getTime() - d1.getTime();
long minutes = TimeUnit.MILLISECONDS.toMinutes(diff);                      
System.out.println("Time in minutes: " + minutes + " minutes.");

But you should consider using Java 8 new Date/Time features, or Joda Time.

Problem

I have this problem with calculating time difference in minutes. Its working fine with exampples like calculating the difference between 2045 and 2300. But when I want to calculate the difference between for example 2330 (today) and 0245 (tomorrow) I get a incorrect answer. Code below: ``` // This example works String dateStart = "2045"; String dateStop = "2300"; // This example doesnt work //String dateStart = "2330"; //String dateStop = "0245"; // Custom date format SimpleDateFormat format = new SimpleDateFormat("HHmm"); Date d1 = null; Date d2 = null; try { d1 = format.parse(dateStart); d2 = format.parse(dateStop); } catch (Exception e) { e.printStackTrace(); } long diff = d2.getTime() - d1.getTime(); long minutes = TimeUnit.MILLISECONDS.toMinutes(diff); System.out.println("Time in minutes: " + minutes + " minutes."); ``` Thanks in advance

Original source