Avoid old date-time classes
Avoid the old date-time classes bundled with the earliest versions of Java, such as java.util.Date/.Calendar. They are poorly designed, confusing, and troublesome.
java.time
The java.time framework built into Java 8 and later supplants the old date-time classes. See Tutorial.
For use with Java 6 & 7, check out the ThreeTen-Backport project ('ThreeTen' refers to JSR 310 defining java.time). For Android specifically, see the Android wrapper around the Backport, ThreeTenABP.
The new classes include LocalDate
for a date-only value without time-of-day and without time zone. Another handy class you need is the enum DayOfWeek
. Use these objects rather than strings to make your code type-safe, self-documenting, and localization-ready.
Reminder: Java provides special high-performance Set
and Map
implementations for enums, EnumSet
and EnumMap
.
EnumSet<DayOfWeek> dayOfWeekSet = EnumSet.of( DayOfWeek.TUESDAY , DayOfWeek.THURSDAY );
Define a date interval.
LocalDate start = LocalDate.of( 2016 , Month.MARCH , 1 );
LocalDate stop = start.plusDays( 10 );
Define a collection to keep our targeted dates.
List<LocalDate> localDates = new ArrayList<>();
Loop the days in that interval. In date-time work we commonly use the Half-Open approach where the beginning in inclusive while the ending is exclusive.
LocalDate localDate = start;
while ( localDate.isBefore( stop ) ) {
if ( dayOfWeekSet.contains ( localDate.getDayOfWeek() ) ) {
localDates.add( localDate );
}
// Prepare for next loop.
localDate = localDate.plusDays( 1 );
}
Dump to console.
System.out.println( "From: " + start + " to: " + stop + " the dates for days-of-week: " + dayOfWeekSet + " = " + localDates );
From: 2016-03-01 to: 2016-03-11 the dates for days-of-week: [TUESDAY, THURSDAY] = [2016-03-01, 2016-03-03, 2016-03-08, 2016-03-10]
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?
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.