Converting date to localdate in java

3 Examples to Convert Date to LocalDate in Java 8? Tutorial

One of the great features of Java 8 is the new Date and Time API which is intended to fix existing issues related to mutability and thread-safety with existing java.util.Date class. But given java.util.Date is used very heavily across all the Java applications, you will often end up with a situation where you need to convert java.uti.Date to java.time.LocalDate while working in Java 8. Unfortunately there is no toLocalDate() method in the java.util.Date class. Though, you can easily convert Date to LocalDate if you are familiar with how new and old API classes map to each other.

Читайте также:  Python pyqt5 button click

The equivalent class of java.util.Date in new Date and Time API in java.time.Instant because Date actually represents an instance of time-line, not a date. That’s why you also have a toInstant() method on the Date class.

Despite its name, java.util.Date represents an instant on the timeline, not a «date». The actual data stored within the object is a long count of milliseconds since 1970-01-01T00:00Z (midnight at the start of 1970 GMT/UTC).

The equivalent class to java.util.Date in JSR-310 is Instant, thus there is a convenient method toInstant() to provide the conversion:

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

A java.util.Date instance has no concept of time-zone. This might seem strange if you call toString() on a java.util.Date , because the toString() is relative to a time-zone. However, that method actually uses Java’s default time-zone on the fly to provide the string. The time zone is not part of the actual state of java.util.Date .

An Instant also does not contain any information about the time zone. Thus, to convert from an Instant to a LocalDate it is necessary to specify a time-zone. This might be the default zone — ZoneId.systemDefault() — or it might be a time-zone that your application controls, such as a time-zone from user preferences. Use the atZone() method to apply the time-zone.

This is a very important concept and if you don’t know much about Date and Time in Java, I suggest you first go through a comprehensive Java course like The Complete Java MasterClass on Udemy to learn in a structured way. It’s one of the most up-to-date and comprehensive courses.

3 Ways to convert java.util.Date to java.time.LocalDate in Java 8

Now that you know the basic concepts of Date and LocalDate class and knows the challenges behind converting Date to LocalDate and vice-versa, it is now time to see some practical code examples to convert java.util.Date to java.time.LocalDate in Java.

Читайте также:  Чем открывать html коды

1. Using Instance and ZonedDateTime

So this is our first method to convert Date to LocalDate in Java. In this example, I have used the Instance and ZondeDateTime classes. In this example, we first convert Date To Instance using the toInstant() method which is added into java.util.Date class.

Date input = new Date(); Instant instant = input.toInstant(); ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());

A ZonedDateTime contains a state consisting of the local date and time, time-zone, and the offset from GMT/UTC. As such the date — LocalDate — can be easily extracted using toLocalDate() :

Date input = new Date(); Instant instant = input.toInstant(); ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault()); LocalDate date = zdt.toLocalDate();

2. Using Instant and Date.getTime()

This is another way to convert the old Date to a new LocalDate instance in Java. In this method, you use the Instance.ofEpochMilli() method to create a ZonedDateTime and then you convert that to LocalDate using the built-in toLocalDate() method as shown below:

Date date = new Date (System.currentTimeMillis()); LocalDate ld = Instant.ofEpochMilli(date.getTime()) .atZone(ZoneId.systemDefault()).toLocalDate()

3. Using java.sql.Date

This is the third and the easiest way to convert a java.util.Date to LocalDate in Java. In this example, we first convert java.util.Date to java.sql.Date which just contains date without the time and then we use toLocalDate() method added on java.sql.Date to create a LocalDate object, easy isn’t it?

LocalDate ld = new java.sql.Date( new java.util.Date().getTime() ) .toLocalDate();

You can see here we have used the technique you have learned while converting the java.util.Date to SQL date and once you have java.sql.Date you can directly call the toLocalDate() method, which makes it really easy.

If you are thinking about how this is possible, it is possible because unlike java.util.Date which contains both Date and Time portion, both java.sql.Date and java.time.LocalDate doesn’t contain any time portion.

In other words, here we are just stripping out time portion of java.util.Date by converting into SQL date and then converting to LocalDate. And it simplest realization: LocalDate.of(getYear() + 1900, getMonth() + 1, getDate()) because year starts from 1900 and month are zero-based in old API

If you are wondering how does a new Date and Time API looks, here is a nice diagram which shows class hierarchy of Java 8 Date and Time API:

3 Ways to convert java.util.Date to java.time.LocalDate in Java 8

That’s all about how to convert java.util.Date to java.time.LocalDate in Java 8. This is a very common task for Java programmers to write code every day. I strongly suggest you understand the concepts and learn the techniques demonstrated in this article to avoid using Google every time you need to convert an old Date to a new Local Date object. It may seem difficult the first time, but once you understand the API and how it works, it’s very easy to remember.

  • 5 Courses to learn Java 8 in-depth
  • 5 Books to Learn Java 8 from Scratch
  • How to sort HasMap by values in Java 8?
  • How to convert Date to LocalDate in Java 8?
  • How to parse String to LocalDate in Java 8?
  • How to join String in Java 8
  • How to get the current Day, Month, and Year from LocalDate in Java 8?
  • How to convert Date to LocalDateTime in Java 8?
  • 5 Reasons to Avoid Old Date and Time API of Java
  • 8 Best Courses to master Stream and Lambdas in Java
  • 7 Best Courses to learn Java Collections in depth
  • 11 Advanced Core Java Courses for experienced Developers
  • 21 Books Java Developer Should Read in depth

P. S. — If you are looking for some free courses to learn recent changes on Java 8 and Java 9 then you can also see this list of Free Java 8 and 9 Courses for Programmers.

Источник

How to Convert Date to LocalDate

In this post we will look how to convert Date to LocalDate in Java. We will also convert LocalDateTime to Date.

1. Convert Date to LocalDate

Java 8 introduces a new API to work with date and time. In this section, let’s see how to convert Date to LocalDate with Java.

1.1 Date To LocalDate

Date date = new Date(); LocalDate localDate = Instant.ofEpochMilli(date.getTime()) .atZone(ZoneId.systemDefault()) .toLocalDate(); System.out.println(date); //Thu Oct 01 16:10:58 PDT 2020

2. Convert LocalDate to Date

There might be some use case where we like to convert LocalDate to Date in Java. This section will take a look at this option.

LocalDate localDate = LocalDate.now(); Date date = Date.from(localDate.atStartOfDay() .atZone(ZoneId.systemDefault()) .toInstant()); System.out.println(date); //Thu Oct 01 00:00:00 PDT 2020 Date date2 = Date.from(localDate.atStartOfDay( ZoneId.systemDefault()) .toInstant()); System.out.println(date2); //Thu Oct 01 00:00:00 PDT 2020

3. DateUtils for Conversion

It’s always a best to create your own small utility class to perform the date conversion. Let’s write a small utility class to perform the following for us, and we can use it throughout our project.

  1. Convert Date to LocalDate using system default ZoneId .
  2. Date to LocalDate using supplied ZoneId .
  3. Convert LocalDate back to Date in Java using
package com.javadevjournal.date; import java.time.*; import java.util.Date; public final class JDJDateUtils < public static LocalDate convertToLocalDate(Date date) < return Instant.ofEpochMilli(date.getTime()) .atZone(ZoneId.systemDefault()) .toLocalDate(); >public static LocalDate convertToLocalDate(Date date, ZoneId zoneId) < return Instant.ofEpochMilli(date.getTime()) .atZone(zoneId) .toLocalDate(); >public static Date convertToDate(LocalDate date) < return Date.from(date .atStartOfDay().atZone( ZoneId.systemDefault()) .toInstant()); >public static Date convertToDate(LocalDate date, ZoneId zoneId) < return Date.from(date .atStartOfDay().atZone( zoneId) .toInstant()); >>

Источник

Java Date to LocalDate

Convert Date to LocalDate in java

In this post, we will see how to convert Date to LocalDate in java.

Sometimes, we may need to convert Date to new Java 8 APIs and vice versa. There are multiple ways to convert Date to LocalDate in java.

Using toInstant() method of Date class

You can convert Date to LocalDate using toInstant() method of Date class. Since Instant objects are time agnostic, you need to use atZone() method to convert to derive LocalDate from it.
Here is an example:

Using toInstant() method of Date class

You can convert Date to LocalDate using toInstant() method of Date class. You can use Intant.ofEpochMilli(date.getTime()) to derive instant object and use atZone() method to associate time zone to instant object.
Here is an example:

Using java.sql.Date

You can convert Date to LocalDate using java.sql.Date . In Java 8, there is new method toLocalDate() added to java.sql.Date class.`
Here is an example:

That’s all about how to convert Date to LocalDate in java

Was this post helpful?

You may also like:

[Fixed] Unable to obtain LocalDateTime from TemporalAccessor

Convert LocalDate to Instant in Java

Convert Instant to LocalDate in Java

Convert String to LocalDateTime in Java

Format LocalDateTime to String in Java

Java 8 – Find duplicate elements in Stream

How to format Instant to String in java

Java LocalDate to Date

Java Stream to List

Convert LocalDateTime to Timestamp in Java

Share this

Author

Convert Set to String in Python

Table of ContentsWays to convert set to string in PythonUsing the str() functionUsing the repr() functionUsing the join() functionUsing the map() functionConclusion Sets are an unordered collection of elements in Python. It does not contain duplicate elements and can be defined using the set() function in Python. Ways to convert set to string in Python […]

Convert String to Array in java

Convert String to Array in Java

Table of ContentsHow to convert String to Array in JavaUsing toArray() method of SetUsing the split() method of String classUsing StringTokenizor classUsing the split() method of StringUtils classUsing split() method of Pattern classConclusion When developing applications in Java there are many cases where we will find ourselves converting data from one type to the other. […]

Convert float to int in Python

Convert float to int in Python

Table of ContentsUsing the int() function to convert float to int in PythonUsing the math module functions to convert float to int in PythonUsing ceil()Using trunc()Using floor Python provides several in-built functions and modules for datatype conversions. Floating-point numbers can be easily converted to integers using some of these in-built functions. This tutorial will discuss […]

Java BigDecimal to Double

Java BigDecimal to Double

Java Set to Array

Java Set to Array

Table of Contents1. Using Java 8’s Stream2. Using toArray()3. Using toArray(IntFunction) [Java 11]4. Using System.arraycopy()5. Using Arrays.copyOf6. Using simple iteration7. Using Guava library7.1 Using FluentIterable7.2 Using Iterables In this post, we will learn java set to array conversion. There are many ways to convert set to an array. 1. Using Java 8’s Stream If you […]

Convert LocalDate to Date in java

Java LocalDate to Date

Table of ContentsUsing Instant objectUsing java.sql.Date In this post, we will see how to convert LocalDate to Date. Java 8 has introduced a lot of new APIs for Date and time. There can be many ways to convert Java LocalDateTime to date. Using Instant object You can convert LocalDate to Date using Instant object which […]

Источник

Оцените статью