tl;dr
ChronoUnit.DAYS.between( today , firstOfNextMonth )
java.time
Determining a current date requires a time zone. For any given moment, the date varies around the globe by time zone.
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Africa/Casablanca" ) ;
LocalDate today = LocalDate.now( z ) ;
From that, get an object to represent the entire month, the current YearMonth
.
YearMonth ym = YearMonth.from( today ) ;
From that, ask for first of next month. Generally the best practice for handling a span of time is the Half-Open approach. The beginning is inclusive while the ending is exclusive. So the current month runs up to, but does include, the first of the following month.
LocalDate firstOfNextMonth = ym.plusMonths( 1 ).atDay( 1 ) ;
To get a count of days in total, use the ChronoUnit
enum.
long days = ChronoUnit.DAYS.between( today , firstOfNextMonth ) ;
Dump to console.
System.out.println( days + " days between " + today + " and " + firstOfNextMonth ) ;
See this code run live at IdeOne.com.
30 days between 2017-11-01 and 2017-12-01
FYI, you can use a Period
to track the span of time. Useful for other purposes, but not for a count of days.
Period p = Period.between( today , firstOfNextMonth ) ;
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?