This content originally appeared on DEV Community and was authored by Pratiksha Dixit
When I first started working with dates in Java, I came across java.util.Date
, Calendar
, and java.sql.Date
. At first, I thought they were the standard way of doing things. But the more I used them, the more confusing and frustrating they became.
Here’s what I learned as a student and why I now use the java.time
package for all my date-related logic.
1. java.util.Date
Is Mutable and Confusing
One big issue with java.util.Date
is that it’s mutable. That means if you pass it to a method, that method can change it without you even realizing it. This creates unexpected bugs.
Also, the way it handles years and months is just weird. For example:
Date d = new Date(2025, 7, 16); // Actually means year 3925, not 2025
`
(Yes, it adds 1900 to the year. Why? No idea.)
2. Calendar
Was Meant to Fix It… But It Didn’t
So Java introduced Calendar
to fix the problems in Date
. But honestly, it’s even harder to use. The syntax is bulky and just feels wrong:
java
Calendar cal = Calendar.getInstance();
cal.set(2024, Calendar.JULY, 16);
Date date = cal.getTime();
There’s too much going on for something that should be simple.
3. java.sql.Date
Is Only for JDBC
At one point, I tried using java.sql.Date
everywhere. But I found out it’s only meant for JDBC, not for general use. If you use it in your normal application logic, you’re basically mixing database code with your core logic — and that’s not good practice.
4. The Better Way — java.time.*
Then I discovered java.time
(available since Java 8). It just makes sense. Everything is clean, immutable, and easy to work with.
java
LocalDate today = LocalDate.now();
LocalDate dob = LocalDate.of(2000, 1, 1);
Period age = Period.between(dob, today);
This is how I expect a date API to work.
And if I need to use it with JDBC, I can convert it:
java
LocalDate localDate = LocalDate.now();
java.sql.Date sqlDate = java.sql.Date.valueOf(localDate);
Final Thoughts
If you’re a beginner like me, I really suggest skipping the old date/time classes unless you’re working with legacy code. Stick to java.time
— it’s clean, safe, and built for modern Java.
Just wanted to share this little realization in case it helps someone else struggling with Java date handling like I did.
Let me know if you faced something similar or found your own way to handle dates!
`
This content originally appeared on DEV Community and was authored by Pratiksha Dixit