Search code examples
javatimetimerschedulerlocaldate

Getting remaining minutes/hours between current time and the next saturday?


I've been looking through the docs for the better part of the day now and have been unable to figure out how exactly this should be done.

I'm looking to run an event every week, every saturday at 00:00 until monday 00:00 (48h).

public static void scheduleEvent() {
    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);       

    Long saturdayMidnight = LocalDateTime.now().until(LocalDateTime.now().plusMinutes(1/* ??? */), ChronoUnit.MINUTES);
    scheduler.scheduleAtFixedRate(new EventTimer(), saturdayMidnight, TimeUnit.DAYS.toMinutes(1), TimeUnit.MINUTES);
}

As a test here, I set it to wait a minute till the EventTimer class is called. That works as intended, but how could I calculate the remaining minutes or hours between the current time and saturday midnight, which I could then use in the scheduler to launch the event at the correct time every weekend?

As for the duplicate, I'm not trying to get the date of the upcoming saturday, I'm trying to get the minutes/hours between the current time and the upcoming saturday. Though if it can be accomplished through just dates, I wouldn't mind.


Solution

  • Here is a snippet to get a "next Saturday, midnight" LocalDateTime instance, then the hours and minutes until then.

    // getting next saturday midnight
    LocalDateTime nextSaturdayMidnight = LocalDateTime.now()
        // truncating to midnight
        .truncatedTo(ChronoUnit.DAYS)
        // adding adjustment to next saturday
        .with(TemporalAdjusters.next(DayOfWeek.SATURDAY));
    
    // getting hours until next saturday midnight
    long hoursUntilNextSaturdayMidnight = LocalDateTime.now()
        // getting offset in hours
        .until(nextSaturdayMidnight, ChronoUnit.HOURS);
    
    // getting minutes until...
    long minutesUntilNextSaturdayMidnight = LocalDateTime.now()
        // getting offset in minutes
        .until(nextSaturdayMidnight, ChronoUnit.MINUTES);
    

    Printed at the time of writing (August 14th 14:02), the 3 variables should look like:

    2018-08-18T00:00
    81
    4917