Search code examples
javalocaldate

java create date for dayOfWeek and time without a specific date, i.e. valid for any Monday


How can I create a generic date (i.e. not attached to any actual yyMMdd but similar to:

val START = LocalTime.of(startHour, startMinute)
val END = LocalTime.of(endHour, endMinute)

However, I additionally want to include the dayOfWeek.

My intention is to calculate the overlap of time intervals, i.e. for two given (start, end) timestamps I want to calculate overlap with a specified weekday and time (i.e. like opening hours).

edit

I am not sure if a custom class is good enough. My intention is if I have a list of events like:

id,start,end
1,2018-01-01 08:00, 2018-01-01 08:00 || opening hours 8-10, duration: 1
2,2018-01-01 10:00, 2018-01-01 12:00 || opening hours 8-10, duration: 0
3,2018-01-02 10:00, 2018-01-02 12:00 || opening hours 10-15, duration 2

to validate if time interval of start-end intersects with another time interval (i.e. opening hours), but this other time interval depends on the day of week.

After constructing the object (where I currently have my probably as I can't combine dayOfWeek and Time in a generic way)

I would use isBefore/isAfter a couple of times and then calculate the duration of overlap.


Solution

  • Just use the DayOfWeek enum built into Java. It offers seven predefined objects, one for every day of the week, such as DayOfWeek.MONDAY.

    I don’t follow exactly your business problem, but it sounds like you need to define your own class.

    public class Shift {
        DayOfWeek dayOfWeek ;
        LocalTime startTime , stopTime ;
    }
    

    Add a method that translates that into real moments.

    public ZonedDateTime startAtDate( LocalDate ld , ZoneId z ) {
        LocalDate LocalDate = ld.with( TemporalAdjustors.previousOrSame( this.dayOfWeek ) ) ;
        ZonedDateTime zdt = ZonedDateTime.of( localDate , this.startTime , z ) ;
        return zdt ;
    }
    

    You’ll likely want to add the ThreeTen-Extra library to your project. It offers classes such as Interval and LocalDateTime that you might find useful. These classes offer a bunch of comparison methods such as abuts, overlaps, etc.

    Looks like that library lacks a LocalTimeRange, so might want to roll your own. Perhaps even donate such a class to that project.


    About java.time

    The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

    The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

    To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

    You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

    Where to obtain the java.time classes?