Skip to content
Advertisement

How to avoid using milliseconds when using OffsetDateTime.now()

I am using OffsetDateTime.now() to get the current date in UTC format and result includes milliseconds too. I don’t want milliseconds to be sent . Is there a way i can remove Milliseconds from OffsetDateTime.now() without using split.

Current format: 2021-02-11T11:27:27.846871-08:00
Format i am looking: 2021-02-10T16:04:00-08:00

Advertisement

Answer

tl;dr

myOffsetDateTime.truncatedTo( ChronoUnit.SECONDS ) 

Details

The date-time classes such as OffsetDateTime are not strings. They do not have a format. Rather than thinking in terms of string manipulation, think in terms of the date-time logic.

The OffsetDateTime class offers a truncatedTo method for setting smaller parts to zero. Pass a ChronoUnit to specify the granularity of your truncation. Specify ChronoUnit.SECONDS to set the fraction-of-second (a number of nanoseconds) to zero.

OffsetDateTime nowUtc = OffsetDateTime.now( ZoneOffset.UTC ) ;
OffsetDateTime nowUtcTruncated = nowUtc.truncatedTo( ChronoUnit.SECONDS ) ;

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement