tl;dr
MonthDay.from( zdt ).equals(
MonthDay.of(
Month.DECEMBER ,
Month.DECEMBER.maxLength()
)
)
java.time
The Joda-Time project is now in maintenance mode, and advises migrating to the java.time classes built into Java.
These include the MonthDay
class to represent a day-of-month without year. We know the last day of year is always December 31. We make a constant for that value. To guard against silly mistakes, we ask for the length of the month rather than hard-code 31
.
static final public MonthDay MONTHDAY_END_OF_YEAR = MonthDay.of( Month.DECEMBER , Month.DECEMBER.maxLength() );
The equivalent class to Joda-Time DateTime
in java.time is ZonedDateTime
.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.now( z );
Ask for the MonthDay
.
MonthDay md = MonthDay.from( zdt );
Compare to our constant.
Boolean isLastDay = md.equals( MONTHDAY_END_OF_YEAR );
TemporalAdjuster
By the way, there is a TemporalAdjuster
for getting last day of the year: TemporalAdjusters.lastDayOfYear()
(note the plural 's').
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdtNow = ZonedDateTime.now( z );
ZonedDateTime zdtLastDayOfYear = zdtNow.with( TemporalAdjusters.lastDayOfYear() ) ;
MonthDay mdYearEnd = MonthDay.from( zdtLastDayOfYear );
Dump to console.
System.out.println( "zdtNow: " + zdtNow );
System.out.println( "zdtLastDayOfYear: " + zdtLastDayOfYear );
System.out.println( "mdYearEnd: " + mdYearEnd );
zdtNow: 2016-11-26T15:44:06.449-05:00[America/Montreal]
zdtLastDayOfYear: 2016-12-31T15:44:06.449-05:00[America/Montreal]
mdYearEnd: --12-31
See live code in IdeOne.com.
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 java.time.
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?
- Java SE 8 and SE 9 and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
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.