Reputation: 27812
How can I convert an java.time.temporal.Temporal
instance to an java.util.Date
instance?
java.time.temporal.Temporal someTemporal = Instant.now();
java.util.Date some Temporal = x(someTemporal);
I have taken a look at Oracle's legacy time trail documentation, but couldn't find a solution that fits.
Upvotes: 8
Views: 17563
Reputation: 16837
I think you've asked this question slightly wrong. Rather, I believe you want How do I convert any java.time concrete class, e.g. Instant, LocalDate, into a Date using a generic interface. TemporalAccessor
I believe is that interface.
@Test
public void convertTemportalAccessorTypeToDate() throws Exception {
Instant instant = Instant.now();
Date expected = Date.from( instant );
TemporalAccessor now = instant;
long nanos = now.getLong( ChronoField.NANO_OF_SECOND );
long epochSeconds = now.getLong( ChronoField.INSTANT_SECONDS );
Date date1 = Date.from( Instant.ofEpochSecond( epochSeconds, nanos ) );
assertThat( date1, is( expected ));
}
that said, the concrete type actually has to support the ChronoField
, and seems to throw UnsupportedTemporalTypeException
if it does not, so maybe wrap in a try catch.
Upvotes: -4
Reputation: 44061
I strongly suggest to leave out any reference to the (too) general interface java.time.temporal.Temporal
and just do this:
java.util.Date some = java.util.Date.from(Instant.now());
Using the interface Temporal
is almost like using java.lang.Object
. You should be as concrete as possible (especially in context of date and time). Even the JSR-310-API officially outputs a warning:
This interface is a framework-level interface that should not be widely used in application code. Instead, applications should create and pass around instances of concrete types, such as LocalDate. There are many reasons for this, part of which is that implementations of this interface may be in calendar systems other than ISO. See ChronoLocalDate for a fuller discussion of the issues.
Upvotes: 11
Reputation: 160
At the bottom it has:
Although the java.time.format.DateTimeFormatter provides a powerful mechanism for formatting date and time values, you can also use the java.time temporal-based classes directly with java.util.Formatter and String.format, using the same pattern-based formatting that you use with the java.util date and time classes.
It looks like you may want to use the DateTimeFormatter class, with documentation here and maybe going by something like this example:
LocalDate date = LocalDate.now();
String text = date.format(formatter);
LocalDate parsedDate = LocalDate.parse(text, formatter);
Upvotes: -2