Old Date and Calendar classes
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Before Java 8, dates were handled by java.util.Date, java.util.Calendar and java.text.SimpleDateFormat. They are still found in old projects and libraries, but new code uses java.time and converts old values at the edges.
Why Date and Calendar are avoided
java.util.Date (Java 1.0) has a misleading name: it is not a date but a moment, stored as milliseconds since 1970 in UTC.
Example 1 · Calendar: months from 0 and lenient rollover
import java.util.Calendar;import java.util.GregorianCalendar;
public class CalendarTrapDemo { public static void main(String[] args) { Calendar cal = new GregorianCalendar(2024, 3, 15); // meant 15 March System.out.println("Calendar.JANUARY = " + Calendar.JANUARY); System.out.println("MONTH field: " + cal.get(Calendar.MONTH)); System.out.println("Is it April? " + (cal.get(Calendar.MONTH) == Calendar.APRIL));
cal.set(Calendar.DAY_OF_MONTH, 32); // no error System.out.println("After day 32: month " + cal.get(Calendar.MONTH) + ", day " + cal.get(Calendar.DAY_OF_MONTH));
cal.add(Calendar.DAY_OF_MONTH, 1); // changes cal itself System.out.println("After add(1): day " + cal.get(Calendar.DAY_OF_MONTH)); }}Calendar.JANUARY = 0 MONTH field: 3 Is it April? true After day 32: month 4, day 2 After add(1): day 3
What this code does
- Writing 3 for March gives April, because
Calendarcounts months from 0.LocalDate.of(2024, 3, 15)has no such trap. - Setting day 32 of April quietly rolls over to 2 May (month 4) instead of failing, and
addchanges the calendar object itself.java.timerejects bad values and returns new objects.
Example 2 · A final Date field can still change
import java.time.Instant;import java.time.LocalDate;import java.util.Date;
class Exam { private final Date date;
Exam(Date date) { this.date = date; }
Date getDate() { return date; }}
class ModernExam { private final LocalDate date;
ModernExam(LocalDate date) { this.date = date; }
LocalDate getDate() { return date; }}
public class MutableDateDemo { public static void main(String[] args) { Exam exam = new Exam(Date.from(Instant.parse("2024-03-15T04:30:00Z"))); exam.getDate().setTime(Instant.parse("2024-04-01T04:30:00Z").toEpochMilli()); System.out.println("Old exam date now: " + exam.getDate().toInstant());
ModernExam modern = new ModernExam(LocalDate.of(2024, 3, 15)); modern.getDate().plusDays(17); // returns a new date; the exam is safe System.out.println("Modern exam date: " + modern.getDate()); }}Old exam date now: 2024-04-01T04:30:00Z Modern exam date: 2024-03-15
What this code does
finalstops the field from pointing to another object, but aDateobject itself can be changed withsetTime. Any caller ofgetDate()moved the exam to 1 April.- A
LocalDatecannot be changed at all, so returning it from a getter is safe. WithDate, classes had to copy it in the constructor and the getter to protect themselves.
Its toString() prints that moment in the computer's default zone, so the same object prints differently on a laptop in Pune and a server in Ohio. Its old getters are deprecated: getYear() returns the year minus 1900, and getMonth() counts from 0.
Calendar (Java 1.1) was meant to fix this, but it also counts months from 0: Calendar.JANUARY is 0, so new GregorianCalendar(2024, 3, 15) is April 15. It is lenient by default, which means it quietly rolls invalid values over: day 32 of April becomes 2 May.
Both classes are mutable: setTime, set and add change the object itself. A Date stored in a final field can still be changed by anyone who holds a reference to it. To add to the confusion, java.sql.Date (a date for databases) has the same simple name as java.util.Date.
Find the bug
Spot the old-API trap
Each snippet uses the old API. Tap the line that goes wrong, then check the fix.
Build 15 August 2026 with the old Date class.
Round 1 of 3SimpleDateFormat is not thread-safe
SimpleDateFormat formats and parses Date values with patterns like dd-MM-yyyy. Inside, it keeps a Calendar object that it changes while working. A thread is a separate path of execution in a program; a web server runs many at once, one per request.
Example 3 · SimpleDateFormat parses 31 February
import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.TimeZone;
public class SimpleDateFormatDemo { public static void main(String[] args) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); sdf.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
Date d = sdf.parse("31-02-2024"); System.out.println("Lenient parse: " + sdf.format(d));
sdf.setLenient(false); try { sdf.parse("31-02-2024"); } catch (ParseException e) { System.out.println("Strict parse: " + e.getMessage()); } }}Lenient parse: 02-03-2024 Strict parse: Unparseable date: "31-02-2024"
What this code does
- By default the parser rolls 31 February over into March and reports no problem.
setLenient(false)turns that off, and a checkedParseExceptionmust be handled. - The same
sdfobject also changes its own internal state on every call, which is why sharing it between threads breaks.DateTimeFormatterhas neither problem.
If two threads share one static SimpleDateFormat, they overwrite each other's half-finished work. The result is wrong dates or random exceptions, and only under load, so the bug rarely shows up in testing. Old code worked around it with a new object per call, synchronized blocks or ThreadLocal. SimpleDateFormat is also lenient by default, so 31-02-2024 parses as 2 March. The modern answer to both problems is DateTimeFormatter: immutable, thread-safe and strict when you ask.
Converting old values for old code
You will meet old types in JDBC code, older libraries and legacy APIs. Do not rewrite everything. Convert at the boundary, work with java.time inside, and convert back only when an old method needs it. Each old class got conversion methods in Java 8.
Example 4 · Converting old types to java.time and back
import java.sql.Timestamp;import java.time.Instant;import java.time.LocalDate;import java.time.LocalDateTime;import java.time.ZoneId;import java.time.ZonedDateTime;import java.util.Calendar;import java.util.Date;import java.util.GregorianCalendar;import java.util.TimeZone;
public class ConvertLegacyDemo { public static void main(String[] args) { ZoneId india = ZoneId.of("Asia/Kolkata");
Date oldDate = Date.from(Instant.parse("2024-03-15T14:30:00Z")); Instant instant = oldDate.toInstant(); System.out.println("Date -> Instant: " + instant); System.out.println("Date -> LocalDate IST: " + instant.atZone(india).toLocalDate());
GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("Asia/Kolkata")); cal.clear(); cal.set(2024, Calendar.MARCH, 15, 20, 0); ZonedDateTime zdt = cal.toZonedDateTime(); System.out.println("Calendar -> Zoned: " + zdt);
java.sql.Date sqlDate = java.sql.Date.valueOf(LocalDate.of(2024, 3, 15)); System.out.println("sql.Date -> LocalDate: " + sqlDate.toLocalDate());
Timestamp ts = Timestamp.valueOf(LocalDateTime.of(2024, 3, 15, 20, 0)); System.out.println("Timestamp -> LDT: " + ts.toLocalDateTime());
try { sqlDate.toInstant(); } catch (UnsupportedOperationException e) { System.out.println("sql.Date.toInstant(): UnsupportedOperationException"); } }}Date -> Instant: 2024-03-15T14:30:00Z Date -> LocalDate IST: 2024-03-15 Calendar -> Zoned: 2024-03-15T20:00+05:30[Asia/Kolkata] sql.Date -> LocalDate: 2024-03-15 Timestamp -> LDT: 2024-03-15T20:00 sql.Date.toInstant(): UnsupportedOperationException
What this code does
- Each old type has a matching new one:
DateandInstantare both moments,java.sql.DateandLocalDateare both plain dates,TimestampandLocalDateTimeare both date-times. ACalendarwith a zone becomes aZonedDateTime. java.sql.Dateis written in full becausejava.util.Dateis also imported. It has no time part, sotoInstant()throws;toLocalDate()is the right method.
Example 5 · Wrapping an old API with java.time
import java.time.Instant;import java.time.LocalDate;import java.time.ZoneId;import java.time.temporal.TemporalAdjusters;import java.util.Date;
class LegacyBillingApi { static Date lastPaymentDate() { return Date.from(Instant.parse("2024-01-31T09:00:00Z")); }
static String sendReminder(Date when) { return "Reminder queued for " + when.toInstant(); }}
public class LegacyWrapperDemo { static final ZoneId INDIA = ZoneId.of("Asia/Kolkata");
public static void main(String[] args) { // convert in at the boundary LocalDate lastPaid = LegacyBillingApi.lastPaymentDate().toInstant().atZone(INDIA).toLocalDate();
// all logic in java.time LocalDate nextDue = lastPaid.plusMonths(1); LocalDate monthEnd = nextDue.with(TemporalAdjusters.lastDayOfMonth()); System.out.println("Last paid: " + lastPaid); System.out.println("Next due: " + nextDue); System.out.println("Month end: " + monthEnd);
// convert out only when calling old code: 9 AM IST on the due date Date reminder = Date.from(nextDue.atTime(9, 0).atZone(INDIA).toInstant()); System.out.println(LegacyBillingApi.sendReminder(reminder)); }}Last paid: 2024-01-31 Next due: 2024-02-29 Month end: 2024-02-29 Reminder queued for 2024-02-29T03:30:00Z
What this code does
- The old API speaks
Date, so the program converts once on the way in (toInstant().atZone(...).toLocalDate()) and once on the way out (Date.from(...)). - Everything in between uses
java.time, with its month-end rule and adjusters. 9 AM in India on 29 February is 03:30 UTC, which is what the old API receives.
Date↔Instant:date.toInstant()andDate.from(instant). Add a zone to get a local date:date.toInstant().atZone(ZoneId.of("Asia/Kolkata")).toLocalDate().GregorianCalendar→ZonedDateTime:cal.toZonedDateTime(); back withGregorianCalendar.from(zdt).java.sql.Date↔LocalDate:sqlDate.toLocalDate()andjava.sql.Date.valueOf(localDate).java.sql.Timestamp↔LocalDateTime:ts.toLocalDateTime()andTimestamp.valueOf(localDateTime).
java.sql.Date.toInstant() throws UnsupportedOperationException, because it holds only a date. Use toLocalDate() instead.Clock for code that is easy to test
A method that calls LocalDate.now() inside is hard to test: the answer changes every day, and you cannot check what happens on the due date or on 29 February.
Example 6 · Clock: test "is the fee late?" on any date
import java.time.Clock;import java.time.Duration;import java.time.Instant;import java.time.LocalDate;import java.time.ZoneId;
class FeeService { private final Clock clock;
FeeService(Clock clock) { this.clock = clock; }
boolean isLate(LocalDate due) { LocalDate today = LocalDate.now(clock); return today.isAfter(due); }}
public class ClockDemo { public static void main(String[] args) { ZoneId india = ZoneId.of("Asia/Kolkata"); LocalDate due = LocalDate.of(2024, 3, 15);
// the real app would use: new FeeService(Clock.system(india)) Clock onDueDay = Clock.fixed(Instant.parse("2024-03-15T06:00:00Z"), india); Clock lateNight = Clock.fixed(Instant.parse("2024-03-15T20:00:00Z"), india); Clock weekLater = Clock.offset(onDueDay, Duration.ofDays(7));
System.out.println("On due day: " + LocalDate.now(onDueDay) + " late=" + new FeeService(onDueDay).isLate(due)); System.out.println("20:00 UTC: " + LocalDate.now(lateNight) + " late=" + new FeeService(lateNight).isLate(due)); System.out.println("A week later: " + LocalDate.now(weekLater) + " late=" + new FeeService(weekLater).isLate(due)); }}On due day: 2024-03-15 late=false 20:00 UTC: 2024-03-16 late=true A week later: 2024-03-22 late=true
What this code does
FeeServicenever callsLocalDate.now()by itself; it asks the clock it was given. A fixed clock makes every run give the same answer, so the late-fee rule can be tested on any day.- The clock's zone matters: 20:00 UTC on 15 March is already 01:30 on 16 March in India, so the fee is late.
Clock.offsetmoves a clock forward, here by a week.
A Clock is an object that gives the current instant and zone. Every now method has a version that takes one: LocalDate.now(clock), LocalDateTime.now(clock), Instant.now(clock). Pass the clock into the class through its constructor. This is called dependency injection: the class receives what it needs instead of creating it. The real app passes Clock.system(ZoneId.of("Asia/Kolkata")). Tests pass Clock.fixed(instant, zone), which always returns the same moment, or Clock.offset(base, duration) to move time forward. The class code stays the same in both cases.
Next step
Check your understanding
11 quick questions