ThreeTen Backport
public static MonthDay toMonthDay(Date utilDate) {
Instant inst = DateTimeUtils.toInstant(utilDate);
ZonedDateTime dateTime = inst.atZone(ZoneId.systemDefault());
return MonthDay.from(dateTime);
}
The MonthDay
class of java.time
is what you need, it’s a date without year, or conversely, a month and a day-of-month. Birthdays and other days to remember are the prime example for its use.
Like this:
Date birthday = // ...
Date today = new Date();
if (toMonthDay(today).equals(toMonthDay(birthday))) {
System.out.println("It’s her birthday");
} else {
System.out.println("It’s not her birthday");
}
On Java 6 you need to use the ThreeTen-Backport, the backport of java.time
to Java 6 and 7.
I am hesitatingly using ZoneId.systemDefault()
to use the JVM’s time zone setting for the conversion. On one hand the Date
would normally assume this time zone; on the other hand this is fragile because the setting can be changed at any time from other parts of your program or other programs running in the same JVM. If you know better, by all means give a time zone like for example ZoneId.of("America/Adak")
If using Java 8 or later and the built-in java.time
, the conversion is a little bit simpler:
ZonedDateTime dateTime = utilDate.toInstant().atZone(ZoneId.systemDefault());
return MonthDay.from(dateTime);
Links