P. Hoang
P. Hoang

Reputation: 461

Remove minutes, seconds, and nanoseconds from OffsetDateTime

Is there a concise way to strip out all the minutes, seconds, and nanoseconds in OffsetDateTime? Here is what I have to do to get what I want.

final OffsetDateTime strippedTime = OffsetDateTime.now().withMinute(0).withSecond(0).withNano(0);
System.out.println(strippedTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.nnnnnnnnn")));

The code above gives me:

2016-11-08 09:00:00.000000000

LocalTime.MIDNIGHT sadly strips the hours away from the object, so it is no use to me. Any suggestions appreciated.

Upvotes: 23

Views: 14634

Answers (2)

Mark Rotteveel
Mark Rotteveel

Reputation: 109087

You can use OffsetDateTime.truncatedTo(TemporalUnit) with ChronoUnit.HOURS:

 OffsetDateTime.now().truncatedTo(ChronoUnit.HOURS)

Upvotes: 51

F. Lumnitz
F. Lumnitz

Reputation: 698

You can use OffsetDateTime.now().truncatedTo(ChronoUnit.HOURS)

Upvotes: 9

Related Questions