I want to get Year, Month, Day, etc from Java Date to compare with Gregorian Calendar date in Java. Is this possible?
Say you're in a hurry. Here's the quickest snippet to make that Date
-> Calendar
transition, extract the year, month and day, and then side-by-side this with another GregorianCalendar
.
Key Points: The get()
of Calendar
finds the YEAR, MONTH, DAY_OF_MONTH for you. Remember, months are sure playing a prank starting at 0.
Embrace the java.time.LocalDate
for efficient solutions
When it became clear that some Date
methods belong with the dinosaurs, java.time.LocalDate
became the knight in shining armor from Java 8 onwards.
Handle time zones with care. They are notorious for messing up with the best-laid plans.
Understand the need of using localized methods when time means everything.
Difference? java.time.Period
shows the way
Has the 'How many days apart?' question ever kept you awake? java.time.Period
comes to the rescue. Your hands needn't get dirty with manual calculations.
Just another reason why java.time is way cool. It keeps date operations intuitive and trouble-free more than ever.
A calendar year isn't just a year!
Using SimpleDateFormat
, remember to choose your year symbols carefully. yyyy
is for calendar year and YYYY
is for week year.
Don't let ISO week date system standards surprise you with unexpected results.
Future-proof code, no metal rust here!
Take note fellow time-travelers! When coding for future you want it to last and adapt to changes in the Java platform. Wave your wands and magic java.time.*
classes turn to gold, replacing the straw of java.util.Date
and java.util.Calendar
.
- Migrate: Replace
Date
withLocalDate
. - Avoid: Use
Calendar.get()
orLocalDate
. - Precise: Be explicit with
ZoneId
. - Efficient:
Period
andDuration
lessen manual hiccups.
With these, you'll like the magic mirror reflecting maintainable and clean code.
Was this article helpful?