The Answers by Allen Z. and by Jon Skeet are both correct.
java.time
Here is an update regarding the modern java.time classes in Java 8+ that supplanted the terribly flawed legacy classes such as Date
.
org.threeten.extra.Interval
& java.time.Instant
Firstly, your DateClass
that represents a span of time need not be invented by you. You can find an already written class in the ThreeTen-Extra library that extends the java.time classes built into Java. There you will find the org.threeten.extra.Interval
class, that represents a pair of java.time.Instant
class.
To use that class, pass a pair of Instant
objects.
Notice that in java.time we do not instantiate by calling new
. Instead we use static
factory methods such as .of
.
Instant now = Instant.now() ;
Instant later = now.plusHours( 1 ) ;
Interval interval = Interval.of( now , later ) ;
From there you call useful methods such as contains
, overlaps
, abuts
, and so on.
org.threeten.extra.LocalDateRange
& java.time.LocalDate
If you want a span of time covering dates only, pass a pair of java.time.LocalDate
objects to get a org.threeten.extra.LocalDateRange
object.
LocalDate today = LocalDate.now() ; // Better to pass the optional time zone.
LocalDate weekLater = today.plusWeeks( 1 ) ;
LocalDateRange dateRange = LocalDateRange.of( today , weekLater ) ;
Again, you can call handy methods like contains
, overlaps
, abuts
, and more.
Date
class had severe design problems and has been outdated the last 10 years. For a date use theLocalDate
class and instantiate it with for exampleLocalDate.of(2011, Month.DECEMBER, 10)
. – Calamus