Home > Java > javaTutorial > How to Efficiently Convert java.util.Date to java.time.LocalDate?

How to Efficiently Convert java.util.Date to java.time.LocalDate?

Patricia Arquette
Release: 2024-12-07 01:18:19
Original
722 people have browsed it

How to Efficiently Convert java.util.Date to java.time.LocalDate?

Conversion of java.util.Date to java.time.LocalDate

Problem:

How can you efficiently convert a java.util.Date object to the newer java.time.LocalDate format introduced in JDK 8/JSR-310?

Short Answer:

To achieve the conversion, use the following code:

Date input = new Date();
LocalDate date = input.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
Copy after login

Java 9 Solution:

A more efficient alternative has been added in Java SE 9:

Date input = new Date();
LocalDate date = LocalDate.ofInstant(input.toInstant(), ZoneId.systemDefault());
Copy after login

Explanation:

Unlike its name suggests, a java.util.Date object denotes an instant in time, rather than a specific date. To convert a java.util.Date to a compatible java.time.LocalDate, the following steps are necessary:

  1. Utilize the toInstant() method to obtain an Instant object representing the same instant in time as the Date object.
  2. Apply a specific time zone to the Instant object using the atZone() method. The default system time zone (ZoneId.systemDefault()) can be used or a custom time zone.
  3. Extract the LocalDate object from the resulting ZonedDateTime object using toLocalDate().

This conversion process accounts for the fact that a java.util.Date doesn't contain timezone information. Specifying the time zone enables the accurate conversion to a specific local date.

The above is the detailed content of How to Efficiently Convert java.util.Date to java.time.LocalDate?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template