Joda time - get next time it's X o'clock

Viewed 269

I need to get the next datetime when it's say, 20.00 o'clock.

So for instance, if it's 13.00 hours, it'd give me the datetime corresponding to today at 20.00.

But if it's 21.00, it'd give me tomorrow at 20.00.

How can I achieve this? Is there some built in function that I just can't find the name of?

In a pinch I could also use Java Time instead of Joda Time.

1 Answers

Add one day to DateTime if the time is past 20:00.

Demo:

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalTime;

public final class Main {

    public static final void main(String[] args) {
        // Test
        System.out.println(getNextTime("13.00"));
        System.out.println(getNextTime("21.00"));
    }

    static DateTime getNextTime(String strTime) {
        LocalTime time = LocalTime.parse(strTime);
        DateTime dt = DateTime.now(DateTimeZone.getDefault()).withTime(new LocalTime(20, 0));

        if (time.isAfter(new LocalTime(20, 0))) {
            dt = dt.plusDays(1);
        }
        return dt;
    }
}

Output:

2021-03-29T20:00:00.000+01:00
2021-03-30T20:00:00.000+01:00

Note: Check the following notice at the Home Page of Joda-Time

Joda-Time is the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to java.time (JSR-310).

Using the modern date-time API:

import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public final class Main {

    public static final void main(String[] args) {
        // Test
        System.out.println(getNextTime("13.00"));
        System.out.println(getNextTime("21.00"));
    }

    static ZonedDateTime getNextTime(String strTime) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH.mm");
        LocalTime time = LocalTime.parse(strTime, dtf);
        ZonedDateTime zdt = ZonedDateTime.now(ZoneId.systemDefault()).withHour(20);

        if (time.isAfter(LocalTime.of(20, 0))) {
            zdt = zdt.plusDays(1);
        }
        return zdt;
    }
}

Output:

2021-03-29T20:00:18.325419+01:00[Europe/London]
2021-03-30T20:00:18.327587+01:00[Europe/London]
Related