Dániel Kis
Dániel Kis

Reputation: 2631

How to convert java.time.format.TemoralAccessor to java.util.Date

How can I convert TemporalAccessor to java.util.Date?

TemporalAccessor accessor = functionReturnsTemporalAccessor()
Date date = Date.from(accessor)

Date.from() does not accept TemporalAccessor, is there any way to convert to java.util.Date?

Upvotes: 10

Views: 13124

Answers (2)

kidney
kidney

Reputation: 3083

I suppose it depends on the type of TemporalAccessor your method returns. But the ISO_OFFSET_DATE_TIME output you mentioned in comments should be possible to handle with this:

TemporalAccessor accessor = functionReturnsTemporalAccessor();
Date date = new Date(Instant.from(accessor).toEpochMilli());

Upvotes: 6

Anonymous
Anonymous

Reputation: 86278

DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse(...) returns TemporalAccessor

True. Don’t use that method. Use the one-arg OffsetDateTime.parse(CharSequence) instead. Example:

    String isoOffsetDateTimeString = "2020-11-13T21:07:38.146120+01:00";
    OffsetDateTime dateTime = OffsetDateTime.parse(isoOffsetDateTimeString);
    Instant asInstant = dateTime.toInstant();
    Date oldfashionedDate = Date.from(asInstant);
    System.out.println(oldfashionedDate);

Output in my time zone:

Fri Nov 13 21:07:38 CET 2020

Also don’t use Date if you can avoid it. That class is poorly designed and long outdated. I am assuming that you need one for a legacy API that you cannot afford to upgrade to java.time just now.

The one-arg OffsetDateTime.parse() accepts exactly the format specified by DateTimeFormatter.ISO_OFFSET_DATE_TIME, so is a good replacement for what you were trying.

While it would have been possible to convert the TemporalAccessor returned from DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse() to a Date, only impractical, you generally cannot convert a TemporalAccessor to a Date. Each TemporalAccessor has some fields that it supports and some that it doesn’t. Since a Date (despite the name) is a point in time, the TemporalAccessor would need to define a point in time, and not all TemporalAccessor objects do that.

If you have been used to the old, poorly designed and now long outdated Java date and time classes like SimpleDateFormat and Date, then you have been used calling the methods parse and format on the formatter. With java.time the conventional way is opposite: We now usually call the static parse method on the date-time class, for example OffsetDateTime, optionally giving a DateTimeFormatter as argument (which wasn’t necessary in this case). Similarly we call the format method on the date-time object, again passing a DateTimeFormatter as argument.

Upvotes: 6

Related Questions