javadatejava-timedurationdate-manipulation

Using Duration to check if hours between two days are still within Duration


I was working with LocalDateTime and trying to see if the purchase date(in my case) is withing last x units(days/hours)

I achieved this the following way

 public static final int BOOK_PURCHASED_MIN_HOURS = 72;
 private boolean isWithinAllowedMinTime(LocalDateTime purchaseDateTime) {
    return !LocalDateTime.now(ZoneOffset.UTC).minusHours(BOOK_PURCHASED_MIN_HOURS ).isAfter(purchaseDateTime);
  }

This works perfectly fine and gives me true or false if the book has been purchase in 72 hours

I was wondering something like this can be done but with Duration in java where I do not have to worry about time unit and simply can specify like PT03D or PT72H


Solution

  • I was wondering something like this can be done but with Duration in java where I do not have to worry about time unit and simply can specify like PT03D or PT72H

    Of course, you can do so. You can pass a duration string to your function and parse it to a Duration object to perform a calculation based on it.

    I also recommend you use OffsetDateTime instead of LocalDateTime so that you can use the same offset with OffsetDateTime#now.

    Demo:

    class Main {
        public static void main(String[] args) {
            // Tests    
            System.out.println(isWithinAllowedMinTime(OffsetDateTime.now(ZoneOffset.UTC).minusHours(50), "PT72H")); // true
            System.out.println(isWithinAllowedMinTime(OffsetDateTime.now(ZoneOffset.UTC).minusHours(75), "PT72H")); // false
            System.out.println(isWithinAllowedMinTime(OffsetDateTime.now(ZoneOffset.UTC).minusHours(50), "P3DT12H")); // true
            System.out.println(isWithinAllowedMinTime(OffsetDateTime.now(ZoneOffset.UTC).minusHours(72), "P3DT12H")); // true
            System.out.println(isWithinAllowedMinTime(OffsetDateTime.now(ZoneOffset.UTC).minusHours(90), "P3DT12H")); // false
        }
    
        static boolean isWithinAllowedMinTime(OffsetDateTime purchaseDateTime, String strDuration) {
            Duration duration = Duration.parse(strDuration);
            return !OffsetDateTime.now(purchaseDateTime.getOffset()).minus(duration).isAfter(purchaseDateTime);
        }
    }
    

    Output:

    true
    false
    true
    true
    false
    

    Learn more about the modern Date-Time API from Trail: Date Time.