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.
The Date class in Java internally stores Date in milliseconds. So any date is the number of milliseconds passed since January 1, 1970, 00:00:00 GMT and the Date class provides a constructor which can be used to create Date from milliseconds. The SimpleDateFormat class helps in formatting and parsing of data.
We can convert date to timestamp using the Timestamp class which is present in the SQL package. The constructor of the time-stamp class requires a long value. So data needs to be converted into a long value by using the getTime() method of the date class(which is present in the util package).
We can convert String to Date in java using parse() method of DateFormat and SimpleDateFormat classes.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With