1

Im trying to calculate two dates in a string if its less than 24 hours but I get an error:

java.time.format.DateTimeParseException: Text '20 4 01:40 AM' could not be parsed: 
Unable to obtain LocalDateTime from TemporalAccessor: {DayOfMonth=20, 
MonthOfYear=4},ISO resolved to 01:40 of type java.time.format.Parsed

code:

    String today = "20 4 7:00 AM";
    String tomorrow = "21 4 8:00 AM";

   
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd M h:mm a");

    
    LocalDateTime date1 = LocalDateTime.parse(today, formatter);
    LocalDateTime date2 = LocalDateTime.parse(tomorrow, formatter);

    
    long diffHours = Math.abs(Duration.between(date1, date2).toHours());

    if (diffHours < 24) {
        System.out.println("The difference is less than 24 hours.");
    } else {
        System.out.println("The difference is greater than or equal to 24 hours.");
    }
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Tamara
  • 47
  • 1
  • 8
  • 7
    How would you determine there's less than 24 hours between those "dates"? For all we know this could be April 20 2024 and April 21 1999 or any other year. You might have a look at this instead: https://stackoverflow.com/questions/8523886/how-do-i-simply-parse-a-date-without-a-year-specified - but when setting the default year think about whether you'd want to be able to do the calculation across years, e.g. from Dec 31st to Jan 1st. – Thomas Apr 20 '23 at 08:54
  • 1
    Two special cases: (1) One is on 31 December, the other on January 1. Or the other way around. (2) There is a summer time transition or other time anomaly between the two so that using the duration between the instances of `LocalDateTime` will not correctly determine the difference in your time zone. (3) There are more. Time is complicated. – Ole V.V. Apr 20 '23 at 10:07

0 Answers0