Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.util.date to String using DateTimeFormatter

How can I convert a java.util.Date to String using

 DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss") 

The Date object which I get is passed

DateTime now = new DateTime(date); 
like image 772
Cork Kochi Avatar asked Feb 13 '17 17:02

Cork Kochi


Video Answer


2 Answers

If you are using Java 8, you should not use java.util.Date in the first place (unless you receive the Date object from a library that you have no control over).

In any case, you can convert a Date to a java.time.Instant using:

Date date = ...; Instant instant = date.toInstant(); 

Since you are only interested in the date and time, without timezone information (I assume everything is UTC), you can convert that instant to a LocalDateTime object:

LocalDateTime ldt = instant.atOffset(ZoneOffset.UTC).toLocalDateTime(); 

Finally you can print it with:

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"); System.out.println(ldt.format(fmt)); 

Or use the predefined formatter, DateTimeFormatter.ISO_LOCAL_DATE_TIME.

System.out.println(ldt.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)); 

Note that if you don't provide a formatter, calling ldt.toString gives output in standard ISO 8601 format (including milliseconds) - that may be acceptable for you.

like image 185
assylias Avatar answered Sep 22 '22 05:09

assylias


java.util.Date date = new java.util.Date(System.currentTimeMillis()); Instant instant = date.toInstant();  LocalDateTime ldt = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();  DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss"); System.out.println(ldt.format(fmt)); 
like image 30
Adrian Faur Avatar answered Sep 23 '22 05:09

Adrian Faur