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

EnverOsmanov picture EnverOsmanov · Jun 11, 2015 · Viewed 15.2k times · Source

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

Instant.now().truncatedTo(ChronoUnit.DAYS).toEpochMilli()

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

Answer

Simon picture Simon · Apr 14, 2016

This is what java.time.temporal.TemporalAdjusters are for.

date.with(TemporalAdjusters.firstDayOfMonth()).truncatedTo(ChronoUnit.DAYS);