DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Dynamically Evaluate Dataweave Scripts
  • Iterator Design Pattern In Java
  • Vibe Coding With GitHub Copilot: Optimizing API Performance in Fintech Microservices
  • Writing DTOs With Java8, Lombok, and Java14+

Trending

  • Is Agile Right for Every Project? When To Use It and When To Avoid It
  • Developers Beware: Slopsquatting and Vibe Coding Can Increase Risk of AI-Powered Attacks
  • AWS to Azure Migration: A Cloudy Journey of Challenges and Triumphs
  • Unlocking AI Coding Assistants: Generate Unit Tests
  1. DZone
  2. Coding
  3. Languages
  4. Practical Guide For Converting Between Date and Temporal

Practical Guide For Converting Between Date and Temporal

Check out this practical code guide on converting between Date and Temporal classes in Java.

By 
Anghel Leonard user avatar
Anghel Leonard
DZone Core CORE ·
Nov. 12, 19 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
30.7K Views

Join the DZone community and get the full member experience.

Join For Free

Temporal and Date in Java

Check out this guide on how to convert between Date and Temporal classes in Java.

This article will cover the following Temporal classes— Instant,  LocalDate,  LocalDateTime,  ZonedDateTime, OffsetDateTime,  LocalTime , and OffsetTime.

You may also like: Java Date and Time

Date – Instant

In order to convert from Date to Instant, the solution can rely on the Date.toInstant() method. The reverse can be accomplished via the Date.from(Instant instant) method:

  •  Dateto Instant can be accomplished like this:

Date date = new Date();

// e.g., 2019-02-27T12:02:49.369Z, UTC
Instant instantFromDate = date.toInstant();
  •  Instant to Date  can be accomplished like this:

Instant instant = Instant.now();

// Wed Feb 27 14:02:49 EET 2019, default system time zone
Date dateFromInstant = Date.from(instant);
Keep in mind that  Date  is not time-zone aware, but it is displayed in the system default time zone (for example, via   toString()).   Instantis with a UTC time zone.

Let's quickly wrap these snippets of code in two utility methods, defined in a utility
class — DateConverters:

public static Instant dateToInstant(Date date) {

   return date.toInstant();
}

public static Date instantToDate(Instant instant) {

   return Date.from(instant);
}

Further, let's enrich this class with the methods from the following screenshot:

Image title

The constant from the screenshot,  DEFAULT_TIME_ZONE, is the system default time zone:

public static final ZoneId DEFAULT_TIME_ZONE = ZoneId.systemDefault();


Date – LocalDate

A Date object can be converted to LocalDate via an Instant object. Once we have obtained the Instant object from the given Date object, the solution can apply to it the system default time zone, and call the toLocaleDate() method:

// e.g., 2019-03-01
public static LocalDate dateToLocalDate(Date date) {

   return dateToInstant(date).atZone(DEFAULT_TIME_ZONE).toLocalDate();
}


Converting from LocalDate to Date should take into account that LocalDate doesn't contain a time component as Date, so the solution must supply a time component as the start of the day:

// e.g., Fri Mar 01 00:00:00 EET 2019
public static Date localDateToDate(LocalDate localDate) {

   return Date.from(localDate.atStartOfDay(
      DEFAULT_TIME_ZONE).toInstant());
}


Date – DateLocalTime

Converting from Date to DateLocalTime is the same as converting from Date to  LocalDate, apart from the fact that the solution should call the toLocalDateTime() method as follows:

// e.g., 2019-03-01T07:25:25.624
public static LocalDateTime dateToLocalDateTime(Date date) {

   return dateToInstant(date).atZone(
      DEFAULT_TIME_ZONE).toLocalDateTime();
}


Converting from LocalDateTime to Date is straightforward. Just apply the system default time zone and call  toInstant():

// e.g., Fri Mar 01 07:25:25 EET 2019
public static Date localDateTimeToDate(LocalDateTime localDateTime) {

   return Date.from(localDateTime.atZone(
      DEFAULT_TIME_ZONE).toInstant());
}


Date – ZonedDateTime

Converting Date to ZonedDateTime can be accomplished via the Instant object obtained from the given Date object and the system default time zone:

// e.g., 2019-03-01T07:25:25.624+02:00[Europe/Athens]
public static ZonedDateTime dateToZonedDateTime(Date date) {

   return dateToInstant(date).atZone(DEFAULT_TIME_ZONE);
}


Converting ZonedDateTime to Date is just about converting ZonedDateTime to  Instant:

// e.g., Fri Mar 01 07:25:25 EET 2019
public static Date zonedDateTimeToDate(ZonedDateTime zonedDateTime) {

   return Date.from(zonedDateTime.toInstant());
}


Date – OffsetDateTime

Converting from Date to OffsetDateTime relies on the toOffsetDateTime() method:

// e.g., 2019-03-01T07:25:25.624+02:00
public static OffsetDateTime dateToOffsetDateTime(Date date) {

   return dateToInstant(date).atZone(
      DEFAULT_TIME_ZONE).toOffsetDateTime();
}


An approach for converting from OffsetDateTimeto Date requires two steps. First, convert OffsetDateTime to LocalDateTime. Second, convert LocalDateTime to  Instant with the corresponding offset:

// e.g., Fri Mar 01 07:55:49 EET 2019
public static Date offsetDateTimeToDate(OffsetDateTime offsetDateTime) {

   return Date.from(offsetDateTime.toLocalDateTime()
      .toInstant(ZoneOffset.of(offsetDateTime.getOffset().getId())));
}


Date – LocalTime

Converting Dateto LocalTimecan rely on the LocalTime.toInstant() method as
follows:

// e.g., 08:03:20.336
public static LocalTime dateToLocalTime(Date date) {

   return LocalTime.ofInstant(dateToInstant(date), DEFAULT_TIME_ZONE);
}


Converting LocalTime to Date should take into account that LocalTime doesn't have a date component. This means that the solution should set the date on January 1, 1970, the epoch:

// e.g., Thu Jan 01 08:03:20 EET 1970
public static Date localTimeToDate(LocalTime localTime) {

   return Date.from(localTime.atDate(LocalDate.EPOCH)
      .toInstant(DEFAULT_TIME_ZONE.getRules()
      .getOffset(Instant.now())));
}


Date – OffsetTime

Converting Date to OffsetTime can rely on the OffsetTime.toInstant() method as follows:

// e.g., 08:03:20.336+02:00
public static OffsetTime dateToOffsetTime(Date date) {

   return OffsetTime.ofInstant(dateToInstant(date), DEFAULT_TIME_ZONE);
}


Converting OffsetTime to Date should take into account that OffsetTime doesn't have a date component. This means that the solution should set the date on January 1, 1970, the epoch:

// e.g., Thu Jan 01 08:03:20 EET 1970
public static Date offsetTimeToDate(OffsetTime offsetTime) {

   return Date.from(offsetTime.atDate(LocalDate.EPOCH).toInstant());
}


Done! The complete code is available on GitHub.

If you enjoyed this article, then I'm sure that you will love my book, Java Coding Problems, which contains an entire chapter dedicated to date and time problems.

Further Reading

Java Date and Time

A Deeper Look Into the Java 8 Date and Time API

Object (computer science) Java (programming language) Convert (command) Snippet (programming) Coding (social sciences) Book GitHub

Opinions expressed by DZone contributors are their own.

Related

  • Dynamically Evaluate Dataweave Scripts
  • Iterator Design Pattern In Java
  • Vibe Coding With GitHub Copilot: Optimizing API Performance in Fintech Microservices
  • Writing DTOs With Java8, Lombok, and Java14+

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!