Sub topic 18
Converting to and from Date, Calendar, and java.sql Types
Old code does not go away when a new API arrives. Many libraries, frameworks, and databases still use java.util.Date, java.util.Calendar, and the java.sql date classes. This chapter shows how to move values between those legacy types and java.time. A legacy type is an older class that is still around for compatibility.
The main idea: convert at the edges. Use java.time inside your own code. Convert to an old type only at the point where you hand a value to old code, and convert back as soon as a value comes in.
Why conversion needs a bridge
The old and new classes do not describe time in the same way:
java.util.Dateis a point on the timeline, stored as milliseconds since the epoch. The epoch is 1970-01-01T00:00:00Z. Despite its name,Dateholds no calendar date of its own.Calendaris a point on the timeline plus a time zone and calendar rules.java.sql.Date,java.sql.Time, andjava.sql.Timestampare subclasses ofjava.util.Datebuilt for databases. A subclass is a class that extends another class.
Because Date is really an instant, the natural bridge type is Instant. For Calendar, the bridge is ZonedDateTime, since both carry a zone. For the java.sql types, Java 8 added direct methods to and from the local types.
Date and Instant
Date has two bridge methods. toInstant() turns a Date into an Instant. The static method Date.from(Instant) goes the other way.
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
public class Legacy {
public static void main(String[] args) {
Date legacy = new Date();
Instant instant = legacy.toInstant();
LocalDateTime local = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
Date back = Date.from(instant);
System.out.println(legacy.equals(back)); // true
System.out.println(local); // current date-time; varies per run
}
}The round trip gives back an equal Date. To get a LocalDateTime, you must choose a zone. An instant has no wall-clock time until you say where in the world you are reading the clock.
Precision is lost going back
An Instant stores nanoseconds. A Date stores only milliseconds. Converting an Instant to a Date silently drops the extra digits.
import java.time.Instant;
import java.util.Date;
public class Precision {
public static void main(String[] args) {
Instant precise = Instant.parse("2024-01-01T00:00:00.123456789Z");
Date date = Date.from(precise);
System.out.println(date.toInstant()); // 2024-01-01T00:00:00.123Z
}
}Calendar, ZonedDateTime, and TimeZone
GregorianCalendar is the usual concrete Calendar class. It has toZonedDateTime() and a static from(ZonedDateTime) method. A plain Calendar also has toInstant() if you only need the instant.
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
public class CalendarBridge {
public static void main(String[] args) {
GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("Europe/Paris"));
cal.clear();
cal.set(2024, Calendar.JUNE, 15, 14, 30);
ZonedDateTime zdt = cal.toZonedDateTime();
System.out.println(zdt); // 2024-06-15T14:30+02:00[Europe/Paris]
GregorianCalendar back = GregorianCalendar.from(zdt);
System.out.println(back.get(Calendar.HOUR_OF_DAY)); // 14
System.out.println(cal.toInstant()); // 2024-06-15T12:30:00Z
}
}Notice Calendar.JUNE. In Calendar, months count from 0, so June is 5. In java.time, June is 6. The conversion methods handle this for you. That is one more reason to convert instead of copying fields by hand.
Time zones have their own bridge. TimeZone.toZoneId() gives a ZoneId, and TimeZone.getTimeZone(ZoneId) goes back.
import java.time.ZoneId;
import java.util.TimeZone;
public class ZoneBridge {
public static void main(String[] args) {
TimeZone old = TimeZone.getTimeZone("Asia/Tokyo");
ZoneId zone = old.toZoneId();
System.out.println(zone); // Asia/Tokyo
System.out.println(TimeZone.getTimeZone(zone).getID()); // Asia/Tokyo
}
}The java.sql types
JDBC is Java's standard API for talking to databases. Before Java 8, JDBC used three special classes:
java.sql.Dateholds a date with no time (SQLDATE).java.sql.Timeholds a time with no date (SQLTIME).java.sql.Timestampholds a date and time with nanoseconds (SQLTIMESTAMP).
Each one has a static valueOf method that takes a local type, and a to... method that returns one.
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class SqlBridge {
public static void main(String[] args) {
java.sql.Date sqlDate = java.sql.Date.valueOf(LocalDate.of(2024, 11, 5));
System.out.println(sqlDate); // 2024-11-05
System.out.println(sqlDate.toLocalDate()); // 2024-11-05
java.sql.Time sqlTime = java.sql.Time.valueOf(LocalTime.of(9, 15, 0));
System.out.println(sqlTime); // 09:15:00
System.out.println(sqlTime.toLocalTime()); // 09:15
Timestamp ts = Timestamp.valueOf(LocalDateTime.of(2024, 11, 5, 9, 15, 30, 123456789));
System.out.println(ts); // 2024-11-05 09:15:30.123456789
System.out.println(ts.toLocalDateTime()); // 2024-11-05T09:15:30.123456789
}
}Timestamp also has Timestamp.from(Instant) and toInstant(), because it keeps the full time down to nanoseconds.
A trap: java.sql.Date has no instant
java.sql.Date and java.sql.Time extend java.util.Date, so they inherit a toInstant() method. But they override it to throw an exception. An exception is an error object that stops the normal flow of the program.
import java.time.LocalDate;
public class SqlTrap {
public static void main(String[] args) {
java.sql.Date sqlDate = java.sql.Date.valueOf(LocalDate.of(2024, 11, 5));
try {
sqlDate.toInstant();
} catch (UnsupportedOperationException e) {
System.out.println("toInstant() is not supported");
}
System.out.println(sqlDate.toLocalDate()); // 2024-11-05
}
}This catches people who write a helper that takes any java.util.Date and calls toInstant(). If a java.sql.Date is passed in, the helper fails at run time. Check the real type first, or use toLocalDate().
Quick reference
| Legacy type | To java.time | From java.time |
|---|---|---|
| `java.util.Date` | `date.toInstant()` | `Date.from(instant)` |
| `GregorianCalendar` | `cal.toZonedDateTime()` | `GregorianCalendar.from(zdt)` |
| `Calendar` | `cal.toInstant()` | none; build a `GregorianCalendar` |
| `TimeZone` | `tz.toZoneId()` | `TimeZone.getTimeZone(zoneId)` |
| `java.sql.Date` | `sqlDate.toLocalDate()` | `java.sql.Date.valueOf(localDate)` |
| `java.sql.Time` | `sqlTime.toLocalTime()` | `java.sql.Time.valueOf(localTime)` |
| `java.sql.Timestamp` | `ts.toLocalDateTime()` or `ts.toInstant()` | `Timestamp.valueOf(ldt)` or `Timestamp.from(instant)` |
Common mistakes
- Converting through strings. Calling
toString()on aDateand parsing the result is slow and depends on the default locale and zone. Use the bridge methods. - Forgetting the zone. Going from
DatetoLocalDateneeds aZoneId:date.toInstant().atZone(zone).toLocalDate(). The same instant can be a different date in Tokyo than in New York. - Using
ZoneId.systemDefault()without thinking. A server's default zone can differ from the user's zone. Pass the zone you mean. - Keeping old types in your own code. Convert once at the boundary. Do not pass
Dateobjects through many layers.
Exercise
A library method returns a java.util.Date. You need the calendar date it represents for a user in "America/Chicago". Write the expression that produces a LocalDate.
Show answer
legacyDate.toInstant().atZone(ZoneId.of("America/Chicago")).toLocalDate(). First turn the Date into an Instant, then attach the user's zone to get a ZonedDateTime, then take the date part.
Exercise
A helper method takes a java.util.Date and calls toInstant(). It works in tests but throws UnsupportedOperationException in production. What is the likely cause, and how do you fix it?
Show answer
In production a java.sql.Date (or java.sql.Time) from a database is being passed in. Those subclasses throw from toInstant(). Fix it by converting with sqlDate.toLocalDate() at the database boundary, or better, read the column as a LocalDate with resultSet.getObject(column, LocalDate.class).
Exercise
You run Date.from(Instant.parse("2024-05-01T10:00:00.000999Z")).toInstant(). What does it print, and why?
Show answer
It prints 2024-05-01T10:00:00Z. Date stores only milliseconds, so the 999 microseconds are dropped, leaving zero milliseconds. Instant.toString then omits the empty fraction.