javadatetimejodatimejava-13

Is there a class for encoding a local time of week in Java?


I'm wanting to create a schedule that wraps around week by week.

Because the schedule is the same from one week to the next, the only information I need to store is the day of the week, and the time it occurs. eg. Monday 2:30pm. The actual date isn't important, nor is time zone.

So far I've been writing my code with the day and time separate, using the DayOfWeek enum and the LocalTime type to work with times. But I've started to run into issues with using two variables to manage time instead of just a single convenient type like DateTime. eg. if I want to get a time 3 hours after 11pm on Tuesday, I can use the LocalTime.plus() method to get 2am, but this doesn't account for the day rollover, and I'd have to check and update that separately.

I also want to make sure that whatever solution I have wraps around from the end of week to the start: eg. 5hrs after Sunday 10pm should be Monday 3am.

Is there a class like this that exists in the JDK or is it easy enough to define your own time types? Or would it just be better to work something out using the LocalDateTime that java provides, and ignore the date component somehow?


Solution

  • There is no such built-in class within the JDK, but it should be not too hard to create such a class yourself.

    I think you are on the good track with using LocalTime and DayOfWeek. Make sure to write a class which wraps these two components, and then add methods to add time units to the wrapper object.

    One of the methods could look like something like this:

    public WeekDayTime plusHours(int hours) {
        int plusDays = (hours / 24);
        int plusHours = hours % 24;
        if (this.time.getHours() + plusHours >= 24) {
            plusDays++;
            plusHours -= 24;
        }
        DayOfWeek newDayOfWeek = ...; // Calculate the day of week somehow
        LocalTime newTime = this.time.plusHours(plusHours);
        return new WeekDayTime(newDayOfWeek, newTime);
    }
    

    Alternatively, you could also wrap a LocalDateTime and just hide the date component. This will save you from implementing those calculations. But then make sure you implement for instance the equals method correctly.