Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove minutes, seconds, and nanoseconds from OffsetDateTime

Tags:

java

java-time

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.

like image 446
Phuong Luu Hoang Avatar asked Nov 08 '16 14:11

Phuong Luu Hoang


People also ask

How do I get time from OffsetDateTime?

It obtains an instance of OffsetDateTime from a text string such as 2007-12-03T10:15:30. It gets the range of valid values for the specified field. It converts this date-time to the number of seconds from the epoch of 1970-01-01T00:00:00Z. It returns a copy of this OffsetDateTime with the time truncated.

What is offset in OffsetDateTime?

OffsetDateTime is an immutable representation of a date-time with an offset. This class stores all date and time fields, to a precision of nanoseconds, as well as the offset from UTC/Greenwich. For example, the value "2nd October 2007 at 13:45.30. 123456789 +02:00" can be stored in an OffsetDateTime .


1 Answers

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

 OffsetDateTime.now().truncatedTo(ChronoUnit.HOURS)
like image 74
Mark Rotteveel Avatar answered Sep 30 '22 20:09

Mark Rotteveel