Java - Time difference in minutes

后端 未结 4 1146
不思量自难忘°
不思量自难忘° 2021-01-21 11:12

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 t

4条回答
  •  无人及你
    2021-01-21 11:52

    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.

提交回复
热议问题