Java - Time difference in minutes

后端 未结 4 1144
不思量自难忘°
不思量自难忘° 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:46

    This is a solved problem. If you look at the Joda Time library you'll find all the time and date manipulation functions you could possibly want:

    In your case something along the lines of:

    DateTime first = new DateTime(larger-time);
    DateTime second = new DateTime(smaller-time);
    DateTime difference = first.minusMillis(second.getMillis())
    

    Joda will cope with all the odd edge conditions like rolling over between days/months/years, lengths of months, leap years, daylight savings, timezones...

    0 讨论(0)
  • 2021-01-21 11:49

    You can add if statement to check if this is today, and if no you can add one day to this, since you are comparing time it wont be problem if you add full day

        if(d2.before(d1)){
            d2.setTime(d2.getTime()+86400000);
        }
    

    Try it out

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-21 11:53

    Consider using LocalDate, LocalDateTime, LocalTime ZonedDateTime classes from java.time.* package introduced in Java 8. They are very handy in use as they can address various corner cases (e.g. measuring minutes across different time zones, or during autumn and spring time change).

    The thing to you need to know when you calculate time difference is that:

    • LocalTime contains time only
    • LocalDate contains date only (no time)
    • LocalDateTime contains both (date + time.)
    • ZonedDateTime contains date + time + timezone

    This implies that difference between times will be different when you compare with:

    • LocalTime you can diff only time so 20:45 and 23:30 gives 2:45 of difference
    • LocalDate you cannot calculate any time diffs (contains no time)
    • LocalDateTime you can specify date and time, e.g.: 20:45 on 1Jan and 23:30 on 3Jan . Time difference will be 2:45 and 2 days of difference, or 50:45.
    • ZonedDateTime - same as LocalDateTime plus you takes into account DayLightSavings, so if the clock is changed overnight - it will get reflected.

    Here is a snippet for a LocalDateTime:

        LocalDateTime today2045    = LocalDateTime.of(
                LocalDate.now(),
                LocalTime.parse("20:45"));
        LocalDateTime tomorrow0230 = LocalDateTime.of(
                LocalDate.now().plusDays(1),
                LocalTime.parse("02:30"));
    
        System.out.println("Difference [minutes]: " + 
                Duration.between(today2045, tomorrow0230).toMinutes());
    

    For ZonedDateTime taking into account spring/autumn clock changes:

        ZonedDateTime today2045    = ZonedDateTime.of(
                LocalDate.now(),
                LocalTime.parse("20:45"),
                ZoneId.systemDefault());
        ZonedDateTime tomorrow0230 = ZonedDateTime.of(
                LocalDate.now().plusDays(1),
                LocalTime.parse("02:30"),
                ZoneId.systemDefault());
    
        System.out.println("Difference [minutes]: " + 
                Duration.between(today2045, tomorrow0230).toMinutes());
    

    Some info on constructors can be found in Oracle's tutorial here.

    0 讨论(0)
提交回复
热议问题