Skip to content
Advertisement

Java LocalDateTime remove the milliseconds from UTC timezone

I am trying to truncate milliseconds from a UTC time zone.

I have the code below where I am able to remove milliseconds but I still get the Z at the end.

OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC );
OffsetDateTime eventDateTime=now.minus(4, ChronoUnit.MINUTES);

System.out.println("====Event date Time before truncate===");
System.out.println(eventDateTime);
      
System.out.println("====Event date Time after truncate===");
System.out.println(eventDateTime.truncatedTo(ChronoUnit.SECONDS));

This outputs the following:

====Event date Time before truncate===

2021-03-09T20:46:24.081Z

====Event date Time after truncate===

2021-03-09T20:46:24Z

Advertisement

Answer

The Z is the timezone information. You can convert the OffsetDateTime instance to a LocalDateTime like this:

eventDateTime.truncatedTo(ChronoUnit.SECONDS).toLocalDateTime()
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement