Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert java.time.temporal.Temporal to java.util.Date

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.

like image 552
Abdull Avatar asked Oct 24 '16 15:10

Abdull


People also ask

Do you convert a millisecond to date in Java?

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.

Can we convert date to timestamp in Java?

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).

Can we convert string to date in Java?

We can convert String to Date in java using parse() method of DateFormat and SimpleDateFormat classes.


1 Answers

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.

like image 60
Meno Hochschild Avatar answered Oct 13 '22 00:10

Meno Hochschild