Course contentsShow
← Java
Lesson 1896 of 2,87038. Date and Time API (java.time)Free lesson

Converting Date to Instant

Using Date.toInstant() and Date.from(Instant) to bridge between legacy and modern APIs.

Converting Date to Instant

You'll learn how to bridge legacy java.util.Date with the modern java.time.Instant using two simple conversion methods.

When working with older Java code, you'll often encounter java.util.Date objects. To take advantage of the modern Date and Time API's powerful features, you need to convert these legacy dates into Instant objects—and sometimes convert back for compatibility with old APIs.

The Two Bridge Methods

Java provides two methods that act as a bridge between the old and new worlds:

Date to Instant: toInstant()

The Date class includes a toInstant() method that converts a Date object to an Instant:

Date legacyDate = new Date();
Instant instant = legacyDate.toInstant();

This gives you an Instant representing the same moment in time, with all the benefits of immutability and precision.

Instant to Date: Date.from(Instant)

To go the other direction—perhaps when calling legacy APIs that require a Date—use the static Date.from() method:

Instant instant = Instant.now();
Date legacyDate = Date.from(instant);

This creates a Date object from your Instant, allowing seamless interoperability.

Why This Matters

Think of these methods as translation tools. Just as you'd translate between languages to communicate with different audiences, these methods translate between the old and new time APIs. You can now process dates using modern, safe methods while still maintaining compatibility with legacy code that expects Date objects.

// Full round-trip example
Date original = new Date();
Instant instant = original.toInstant();
Date backToDate = Date.from(instant);

Key Takeaway: Use Date.toInstant() to convert legacy dates into modern Instant objects, and Date.from(Instant) to convert back when interfacing with older APIs that require Date.