Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove milliseconds from LocalTime in java 8

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?

like image 661
Nikolas Avatar asked Aug 27 '14 20:08

Nikolas


People also ask

How do I remove milliseconds from a date?

Use the setSeconds() method to remove the seconds and milliseconds from a date, e.g. date. setSeconds(0, 0) . The setSeconds method takes the seconds and milliseconds as parameters and sets the provided values on the date.

How do you convert milliseconds to LocalDate time?

In case of LocalDate , you can use the toEpochDay() method. It returns the number of days since 01/01/1970. That number then can be easily converted to milliseconds: long dateInMillis = TimeUnit.

What is the default format of LocalTime in Java 8?

LocalTime LocalTime is an immutable class whose instance represents a time in the human readable format. It's default format is hh:mm:ss. zzz.


2 Answers

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     
like image 166
demos74dx Avatar answered Sep 19 '22 13:09

demos74dx


cut to minutes:

 localTime.truncatedTo(ChronoUnit.MINUTES); 

cut to seconds:

localTime.truncatedTo(ChronoUnit.SECONDS); 

Example:

import java.time.LocalTime; import java.time.temporal.ChronoUnit;  LocalTime.now()   .truncatedTo(ChronoUnit.SECONDS)   .format(DateTimeFormatter.ISO_LOCAL_TIME); 

Outputs 15:07:25

like image 30
Mike_vin Avatar answered Sep 16 '22 13:09

Mike_vin