How to remove milliseconds from LocalTime in java 8

Nikolas picture Nikolas · Aug 27, 2014 · Viewed 23.1k times · Source

Using the java.time framework, I want to print time in format hh:mm:ss, but LocalTime.now() gives the time in the format hh:mm:ss,nnn. I tried to use DateTimeFormatter:

DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_TIME;
LocalTime time = LocalTime.now();
String f = formatter.format(time);
System.out.println(f);

The result:

22:53:51.894

How can I remove milliseconds from the time?

Answer

demos74dx picture demos74dx · Oct 8, 2015

Edit: I should add that these are nanoseconds not milliseconds.

I feel these answers don't really answer the question using the Java 8 SE Date and Time API as intended. I believe the truncatedTo method is the solution here.

LocalDateTime now = LocalDateTime.now();
System.out.println("Pre-Truncate:  " + now);
DateTimeFormatter dtf = DateTimeFormatter.ISO_DATE_TIME;
System.out.println("Post-Truncate: " + now.truncatedTo(ChronoUnit.SECONDS).format(dtf));

Output:

Pre-Truncate:  2015-10-07T16:40:58.349
Post-Truncate: 2015-10-07T16:40:58

Alternatively, if using Time Zones:

LocalDateTime now = LocalDateTime.now();
ZonedDateTime zoned = now.atZone(ZoneId.of("America/Denver"));
System.out.println("Pre-Truncate:  " + zoned);
DateTimeFormatter dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
System.out.println("Post-Truncate: " + zoned.truncatedTo(ChronoUnit.SECONDS).format(dtf));

Output:

Pre-Truncate:  2015-10-07T16:38:53.900-06:00[America/Denver]
Post-Truncate: 2015-10-07T16:38:53-06:00