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?
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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With