How do I extract the time from a Java Date object

Question from Meeks#7478:

how can i extract the time (i.e HH:mm:ss) from a java date object?

Take your date

Date d = new Date();

turn it into an Instant

Date d = new Date();
Instant instant = d.toInstant();

make a date time formatter

Date d = new Date();
Instant instant = d.toInstant();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");

interpret your instant in a time zone

Date d = new Date();
Instant instant = d.toInstant();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
ZonedDateTime time = instant.atZone(ZoneId.of("EST"));

then format that with the formatter

Date d = new Date();
Instant instant = d.toInstant();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
ZonedDateTime time = instant.atZone(ZoneId.of("EST"));
String dateString = formatter.format(time);

and then just don't have a Date anymore

Instant instant = Instant.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
ZonedDateTime time = instant.atZone(ZoneId.of("EST"));
String dateString = formatter.format(time);

will the time still be considered a date object

cause my sql column is a date time type

Is it a java.sql.Date or java.sql.TimeStamp?

https://docs.oracle.com/javase/8/docs/api/java/sql/Timestamp.html#toInstant--

https://docs.oracle.com/javase/8/docs/api/java/util/Date.html#toInstant--

Both have a toInstant method which is how you can enter the realm of sane date types.

Both also have a from(Instant) (java.sql.Date extends java.util.Date).

so when im saving to db an instant will be able to be inserted in?

Depends on your driver, but most likely when you insert you will need to convert Date.from(instant).

i see

lemme try

thanks man


<- Index