Localdate to Java.Util.Date and Vice Versa Simplest Conversion

LocalDate to java.util.Date and vice versa simplest conversion?

tl;dr

Is there a simple way to convert a LocalDate (introduced with Java 8) to java.util.Date object? By 'simple', I mean simpler than this

Nope. You did it properly, and as concisely as possible.

java.util.Date.from(                     // Convert from modern java.time class to troublesome old legacy class.  DO NOT DO THIS unless you must, to inter operate with old code not yet updated for java.time.
myLocalDate // `LocalDate` class represents a date-only, without time-of-day and without time zone nor offset-from-UTC.
.atStartOfDay( // Let java.time determine the first moment of the day on that date in that zone. Never assume the day starts at 00:00:00.
ZoneId.of( "America/Montreal" ) // Specify time zone using proper name in `continent/region` format, never 3-4 letter pseudo-zones such as “PST”, “CST”, “IST”.
) // Produce a `ZonedDateTime` object.
.toInstant() // Extract an `Instant` object, a moment always in UTC.
)

Read below for issues, and then think about it. How could it be simpler? If you ask me what time does a date start, how else could I respond but ask you “Where?”?. A new day dawns earlier in Paris FR than in Montréal CA, and still earlier in Kolkata IN, and even earlier in Auckland NZ, all different moments.

So in converting a date-only (LocalDate) to a date-time we must apply a time zone (ZoneId) to get a zoned value (ZonedDateTime), and then move into UTC (Instant) to match the definition of a java.util.Date.

Details

Firstly, avoid the old legacy date-time classes such as java.util.Date whenever possible. They are poorly designed, confusing, and troublesome. They were supplanted by the java.time classes for a reason, actually, for many reasons.

But if you must, you can convert to/from java.time types to the old. Look for new conversion methods added to the old classes.

Table of all date-time types in Java, both modern and legacy

java.util.Datejava.time.LocalDate

Keep in mind that a java.util.Date is a misnomer as it represents a date plus a time-of-day, in UTC. In contrast, the LocalDate class represents a date-only value without time-of-day and without time zone.

Going from java.util.Date to java.time means converting to the equivalent class of java.time.Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = myUtilDate.toInstant();

The LocalDate class represents a date-only value without time-of-day and without time zone.

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

So we need to move that Instant into a time zone. We apply ZoneId to get a ZonedDateTime.

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );

From there, ask for a date-only, a LocalDate.

LocalDate ld = zdt.toLocalDate();

java.time.LocalDatejava.util.Date

To move the other direction, from a java.time.LocalDate to a java.util.Date means we are going from a date-only to a date-time. So we must specify a time-of-day. You probably want to go for the first moment of the day. Do not assume that is 00:00:00. Anomalies such as Daylight Saving Time (DST) means the first moment may be another time such as 01:00:00. Let java.time determine that value by calling atStartOfDay on the LocalDate.

ZonedDateTime zdt = myLocalDate.atStartOfDay( z );

Now extract an Instant.

Instant instant = zdt.toInstant();

Convert that Instant to java.util.Date by calling from( Instant ).

java.util.Date d = java.util.Date.from( instant );

More info

  • Oracle Tutorial
  • Similar Question, Convert java.util.Date to what “java.time” type?


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

  • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
    • Java 9 brought some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • Later versions of Android (26+) bundle implementations of the java.time classes.
    • For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
      • If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….

Table of which java.time library to use with which version of Java or Android

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Convert java.time.LocalDate into java.util.Date type

Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

That assumes your date chooser uses the system default timezone to transform dates into strings.

Convert java.util.Date to java.time.LocalDate

Short answer

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

Explanation

Despite its name, java.util.Date represents an instant on the time-line, 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 local date 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:

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

A ZonedDateTime contains 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();

Java 9 answer

In Java SE 9, a new method has been added that slightly simplifies this task:

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

This new alternative is more direct, creating less garbage, and thus should perform better.

Converting between java.time.LocalDateTime and java.util.Date

Short answer:

Date in = new Date();
LocalDateTime ldt = LocalDateTime.ofInstant(in.toInstant(), ZoneId.systemDefault());
Date out = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());

Explanation:
(based on this question about LocalDate)

Despite its name, java.util.Date represents an instant on the time-line, 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 are convenient methods to provide the conversion to and fro:

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

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 local date-time 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. LocalDateTime has a convenient factory method that takes both the instant and time-zone:

Date in = new Date();
LocalDateTime ldt = LocalDateTime.ofInstant(in.toInstant(), ZoneId.systemDefault());

In reverse, the LocalDateTime the time-zone is specified by calling the atZone(ZoneId) method. The ZonedDateTime can then be converted directly to an Instant:

LocalDateTime ldt = ...
ZonedDateTime zdt = ldt.atZone(ZoneId.systemDefault());
Date output = Date.from(zdt.toInstant());

Note that the conversion from LocalDateTime to ZonedDateTime has the potential to introduce unexpected behaviour. This is because not every local date-time exists due to Daylight Saving Time. In autumn/fall, there is an overlap in the local time-line where the same local date-time occurs twice. In spring, there is a gap, where an hour disappears. See the Javadoc of atZone(ZoneId) for more the definition of what the conversion will do.

Summary, if you round-trip a java.util.Date to a LocalDateTime and back to a java.util.Date you may end up with a different instant due to Daylight Saving Time.

Additional info: There is another difference that will affect very old dates. java.util.Date uses a calendar that changes at October 15, 1582, with dates before that using the Julian calendar instead of the Gregorian one. By contrast, java.time.* uses the ISO calendar system (equivalent to the Gregorian) for all time. In most use cases, the ISO calendar system is what you want, but you may see odd effects when comparing dates before year 1582.

How to convert LocalDate to SQL Date Java?

The answer is really simple;

import java.sql.Date;
...
LocalDate locald = LocalDate.of(1967, 06, 22);
Date date = Date.valueOf(locald); // Magic happens here!
r.setDateOfBirth(date);

If you would want to convert it the other way around, you do it like this:

Date date = r.getDate();
LocalDate localD = date.toLocalDate();

r is the record you're using in JOOQ and .getDate() is the method for getting the date out of your record; let's say you have a date column called date_of_birth, then your get method should be called getDateOfBirth().

Convert java.util.Date to what “java.time” type?

Yes, you definitely should be using the java.time framework whenever possible.

Avoid old date-time classes

The old date-time classes including java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat and such have proven to be poorly designed, confusing, and troublesome. Avoid them where you can. But when you must interoperate with these old types, you can convert between old and new.

Read on for a basic introduction, somewhat over-simplified, to orient you in moving back-and-forth between the old and new date-time classes.

java.time

The java.time framework is defined by JSR 310, inspired by the highly-successful Joda-Time library, and extended by the ThreeTen-Extra project. The bulk of the functionality was back-ported to Java 6 & 7 in the ThreeTen-Backport project, with a further adaptation for Android in the ThreeTenABP project.

What java.time type matches java.util.Date? Well, a java.util.Date object basically represents a moment on the timeline in UTC, a combination of a date and a time-of-day. We can translate that to any of several types in java.time. Each is discussed below. Note that some new methods have been added to the old date-time classes to facilitate conversions.

diagram of converting from java.util.Date/.Calendar through ZonedDateTime (or OffsetDateTime) to the three Local… types

Instant

The building block in java.time is an Instant, a moment on the timeline in UTC with a resolution of nanoseconds.

Generally you should do much of your business logic in UTC. In such work, Instant will be used frequently. Pass around Instant objects, applying a time zone only for presentation to a user. When you do need to apply an offset or time zone, use the types covered further below.

From java.util.Date to Instant

Given that both Instant and java.util.Date are a moment on the timeline in UTC, we can easily move from a java.util.Date to an Instant. The old class has gained a new method, java.util.Date::toInstant.

Instant instant = myUtilDate.toInstant();

You can go the other direction, from an Instant to a java.util.Date. But you may lose information about the fractional second. An Instant tracks nanoseconds, for up to nine digits after the decimal place such as 2016-01-23T12:34:56.123456789Z. Both java.util.Date & .Calendar are limited to milliseconds, for up to three digits after the decimal place such as 2016-01-23T12:34:56.123Z. In this example going from Instant to Date means truncation of the 456789.

java.util.Date myUtilDate = java.util.Date.from(instant);

From java.util.Calendar to Instant

What about a java.util.Calendar instead of a java.util.Date? Internal to the Calendar object, the date-time is tracked as a count of milliseconds from the epoch reference date-time of the first moment of 1970 in UTC (1970-01-01T00:00:00.0Z). So this value can be converted easily to an Instant.

Instant instant = myUtilCalendar.toInstant() ;

From java.util.GregorianCalendar to ZonedDateTime

Even better, if your java.util.Calendar object is actually a java.util.GregorianCalendar you can easily go directly to a ZonedDateTime. This approach has the benefit of retaining the embedded time zone information.

Downcast from the interface of Calendar to the concrete class of GregorianCalendar. Then call the toZonedDateTime and from methods to go back and forth.

if (myUtilCalendar instanceof GregorianCalendar) {
GregorianCalendar gregCal = (GregorianCalendar) myUtilCalendar; // Downcasting from the interface to the concrete class.
ZonedDateTime zdt = gregCal.toZonedDateTime(); // Create `ZonedDateTime` with same time zone info found in the `GregorianCalendar`
}

Going the other direction…

java.util.Calendar myUtilCalendar = java.util.GregorianCalendar.from(zdt); // Produces an instant of `GregorianCalendar` which implements `Calendar` interface.

As discussed above, beware that you may be losing information about the fraction of a second. The nanoseconds in the java.time type (ZonedDateTime) gets truncated to milliseconds in the .Calendar/.GregorianCalendar.

OffsetDateTime

From an Instant we can apply an offset-from-UTC to move into a wall-clock time for some locality. An offset is a number of hours, and possibly minutes and seconds, ahead of UTC (eastward) or behind UTC (westward). The ZoneOffset class represents this idea. The result is an OffsetDateTime object.

ZoneOffset offset = ZoneOffset.of("-04:00"); 
OffsetDateTime odt = OffsetDateTime.ofInstant(instant, zoneOffset);

You can go the other direction, from an OffsetDateTime to a java.util.Date. Extract an Instant and then proceed as we saw in code above. As discussed above, any nanoseconds get truncated to milliseconds (data loss).

java.util.Date myUtilDate = java.util.Date.from(odt.toInstant());

ZonedDateTime

Better yet, apply a full time zone. A time zone is an offset plus rules for handling anomalies such as Daylight Saving Time (DST).

Applying a ZoneId gets you a ZonedDateTime object. Use a proper time zone name (continent/region). Never use the 3-4 letter abbreviations commonly seen such as EST or IST as they are neither standardized nor unique.

ZoneId zoneId = ZoneId.of("America/Montreal");
ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, zoneId);

You can go the other direction, from an ZonedDateTime to a java.util.Date. Extract an Instant and then proceed as we saw in code above. As discussed above, any nanoseconds get truncated to milliseconds (data loss).

java.util.Date myUtilDate = java.util.Date.from( zdt.toInstant() );

And we saw further above that a ZonedDateTime may be converted to a GregorianCalendar.

LocalDate

Sometimes you may want a date-only value, without time-of-day and without time zone. For that, use a java.time.LocalDate object.

See this Question for more discussion, Convert java.util.Date to java.time.LocalDate, especially this Answer written by the main man behind the invention of both Joda-Time and java.time.

The key is to go through a ZonedDateTime (as generated in code above). We need a time zone to determine a date. The date varies around the world, with a new day dawning earlier in the east. For example, after midnight in Paris is a new day while still “yesterday” in Montréal. So while a LocalDate does not contain a time zone, a time zone is required to determine a LocalDate.

LocalDate localDate = zdt.toLocalDate();

Converting in the other direction from LocalDate to a date-time means inventing a time-of-day. You can choose any time-of-day that makes sense in your business scenario. For most people, the first moment of the day makes sense. You may be tempted to hard code that first moment as the time 00:00:00.0. In some time zones, that time may not be valid as the first moment because of Daylight Saving Time (DST) or other anomalies. So let java.time determine the correct time with a call to atStartOfDay.

ZonedDateTime zdt = localDate.atStartOfDay(zoneId);

LocalTime

On rare occasion you may want only a time-of-day without a date and without a time zone. This concept is represented by the LocalTime class. As discussed above with LocalDate, we need a time zone to determine a LocalTime even though the LocalTime object does not contain (does not ‘remember’) that time zone. So, again, we go through a ZonedDateTime object obtained from an Instant as seen above.

LocalTime localTime = zdt.toLocalTime();

LocalDateTime

As with the other two Local… types, a LocalDateTime has no time zone nor offset assigned. As such you may rarely use this. It gives you a rough idea of a date-time but is not a point on the timeline. Use this if you mean some general date and some time that might be applied to a time zone.

For example, “Christmas starts this year” would be 2016-12-25T00:00:00.0. Note the lack of any offset or time zone in that textual representation of a LocalDateTime. Christmas starts sooner in Delhi India than it does in Paris France, and later still in Montréal Québec Canada. Applying each of those areas’ time zone would yield a different moment on the timeline.

LocalDateTime ldt = zdt.toLocalDateTime();

Sample Image



About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

  • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
  • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
  • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
  • Later versions of Android bundle implementations of the java.time classes.
  • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

Truncating java.util.Date to LocalDate *without* toInstant() because java.sql.Date gives UnsupportedOperationException

Often the simplest solutions are the hardest to find:

public LocalDate convertDateObject(java.util.Date suspectDate) {

try {
// Don't do this if there is the smallest chance
// it could be a java.sql.Date!
return suspectDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

} catch (UnsupportedOperationException e) {
// BOOM!!
}

// do this first:
java.util.Date safeDate = new Date(suspectDate.getTime());

return safeDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

}

How to convert java.util.Date to java.sql.Date?

tl;dr

How to convert java.util.Date to java.sql.Date?

Don’t.

Both Date classes are outmoded. Sun, Oracle, and the JCP community gave up on those legacy date-time classes years ago with the unanimous adoption of JSR 310 defining the java.time classes.

  • Use java.time classes instead of legacy java.util.Date & java.sql.Date with JDBC 4.2 or later.
  • Convert to/from java.time if inter-operating with code not yet updated to java.time.





















LegacyModernConversion
java.util.Datejava.time.Instantjava.util.Date.toInstant()
java.util.Date.from( Instant )
java.sql.Datejava.time.LocalDatejava.sql.Date.toLocalDate()
java.sql.Date.valueOf( LocalDate )

Why is there no simple inbult conveter for Date to LocalDate in java?

You might as well ask why there is no built in conversion method to turn a File object into an integer: The 2 types are almost entirely unrelated.

But, I hear you say, hold the phone, rzwitserloot! What the heck are you on about? Date and LocalDate are unrelated???

Yes, they are.

Because java.util.Date is a silly name. That's NOT what j.u.Date represents; that's why all the date-related methods in this object are deprecated. Once you see that a class named Date has a method called getHours that should hopefully be a good indication that whomever named it was, let's just go with 'having an off day'. That aint no date.

j.u.Date represents 'a moment in time'. It is the exact equivalent to java.time.Instant. Its internal storage is a single long representing epoch-millis and nothing more.

This has almost no relationship whatsoever with LocalDate.

Yes, MANY systems use a j.u.Date object as a way to represent the same notion that LocalDate is trying to represent, but that is because those systems messed up, and are using an entirely inappropriate type for it. They may be excused; they just fell for the same trap you did: They got thrown off by the name of this class.

Perhaps one might argue: Okay, but, hey, we live in this world and not a fairytale one, so given that so many times 'I need to convert this j.u.Date to LocalDate' comes up, it should be easier, right? Well, enabling bad behaviour just because it is common – let's just say the word is out on whether that's a good idea. Also, that job rather fundamentally is very very tricky. How do we do this conversion? Should I take the moment in time as represented by the j.u.Date object, check out what the actual calendar date is in the current system default locale (as in, go to where the server is. Now go out the building. Find a person. Ask them: What date is it right now? What do they answer?) – or should they go UTC locale? (Go to Greenwich and ask there. Unless it is summer, then ask: What date was it one hour ago?).

The answers obviously won't be the same in many cases, and yet neither strategy is obviously superior to the other. Thus, making such a convenience method is just going to cause epic reams of confusion. You're missing a crucial bit of info, if not more – the job of converting a j.u.Date to a LocalDate cannot be done without further context unless you're willing to just toss a coin on every missing bit of info you have. You might as well invoke a Random instance's .nextInt(365) to figure it out.



Related Topics



Leave a reply



Submit