tl;dr
Expanding on the good Answer by Singh, using a stream from datesUntil
in Java 9 and later.
today // Determine your beginning `LocalDate` object.
.datesUntil( // Generate stream of `LocalDate` objects.
today.plusMonths( 1 ) // Calculate your ending date, and ask for a stream of dates till then.
) // Returns the stream.
.collect( Collectors.toList() ) // Collect your resulting dates in a `List`.
.toString() // Generate text representing your found dates.
[2018-09-20, 2018-09-21, 2018-09-22, 2018-09-23, 2018-09-24, 2018-09-25, 2018-09-26, 2018-09-27, 2018-09-28, 2018-09-29, 2018-09-30, 2018-10-01, 2018-10-02, 2018-10-03, 2018-10-04, 2018-10-05, 2018-10-06, 2018-10-07, 2018-10-08, 2018-10-09, 2018-10-10, 2018-10-11, 2018-10-12, 2018-10-13, 2018-10-14, 2018-10-15, 2018-10-16, 2018-10-17, 2018-10-18, 2018-10-19]
LocalDate::datesUntil
stream
As of Java 9, you can ask for a stream of dates. Call LocalDate::datesUntil
.
Start by determining today's date. That requires a time zone. For any given moment, the date varies around the globe by zone.
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
LocalDate today = LocalDate.now( z ) ;
Determine your ending date.
LocalDate stop = today.plusMonths( 1 ) ;
Ask for stream of dates from beginning to ending.
Stream< LocalDate > stream = today.datesUntil( today.plusMonths( 1 ) );
Pull the dates from that stream, collecting them into a List
.
List< LocalDate > datesForMonthFromToday = stream.collect( Collectors.toList() );
Print our list of dates, generating text in standard ISO 8601 format.
System.out.println( datesForMonthFromToday );
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.