EnverOsmanov EnverOsmanov - 1 year ago 95
Java Question

Is it possible to truncate date to Month with Java 8?

I want to get the milliseconds truncated to days, I can use


But I can't truncate to
(it throws an exception). Do I need use a Calendar?

Answer Source

One way would be to manually set the day to the first of the month:

import static java.time.ZoneOffset.UTC;
import static java.time.temporal.ChronoUnit.DAYS;

ZonedDateTime truncatedToMonth = ZonedDateTime.now(UTC).truncatedTo(DAYS).withDayOfMonth(1);
System.out.println(truncatedToMonth); //prints 2015-06-01T00:00Z
long millis = truncatedToMonth.toInstant().toEpochMilli();
System.out.println(millis); // prints 1433116800000

Or an alternative with a LocalDate, which is maybe cleaner:

LocalDate firstOfMonth = LocalDate.now(UTC).withDayOfMonth(1);
long millis = firstOfMonth.atStartOfDay(UTC).toEpochSecond() * 1000;
long millis = firstOfMonth.atStartOfDay(UTC).toInstant().toEpochMilli();