How to convert an Instant to a date format?

hari m picture hari m · Jun 2, 2015 · Viewed 161.9k times · Source

I can convert a java.util.Date to a java.time.Instant (Java 8 and later) this way:

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 8);
cal.set(Calendar.MINUTE, 30);
Date startTime = cal.getTime();
Instant i = startTime.toInstant();

Can anybody let me know about the convert that instant to date with a specific date & time format? i.e 2015-06-02 8:30:00

I have gone through api but could not find a satisfactory answer.

Answer

Umberto Raimondi picture Umberto Raimondi · Jun 2, 2015

If you want to convert an Instant to a Date:

Date myDate = Date.from(instant);

And then you can use SimpleDateFormat for the formatting part of your question:

SimpleDateFormat formatter = new SimpleDateFormat("dd MM yyyy HH:mm:ss");
String formattedDate = formatter.format(myDate);