tl;dr
org.threeten.extra.Interval.of( start , end )
Interval
The Interval
class found in the ThreeTen-Extra project contains a pair of java.time.Instant
objects.
The Interval
class has several methods you may find helpful such as contains, overlaps, abuts, intersection, union, and span.
The Interval
class is defined as Half-Open, where the beginning is inclusive while the ending is exclusive. So a noon lunch break interval might start at 12:00:00 (noon) and run up to, but not include, 13:00:00 (1 PM). This approach is wise and practical, and is common in date-time handling.
The Instant
class is built into Java 8 and later. It stores a moment on the timeline in UTC with a resolution of nanoseconds.
Instant start = Instant.now() ;
Instant end = start.plusHours( 2 );
Interval interval = Interval.of( start , end );
Extract either instant by calling getStart
and getEnd
.
To see the Instant
object through the lens of a particular region’s wall-clock time, apply a time zone. The resulting ZonedDateTime
is the very same simultaneous moment on the timeline but with a wall-clock time some number of hours and minutes ahead or behind UTC.
ZoneId z = ZoneId.of( "America/Montreal" ) ; // A few hours behind UTC.
ZonedDateTime zdt = instant.atZone( z ) ;
Map
Create your Map
using the Interval
as the key.
Map< Interval , User > map = new HashMap<>() ;
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.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.