Is it possible to truncate a date to a month using Java 8?

I want the milliseconds to be truncated to a few days, I can use

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

But I cannot truncate to ChronoUnit.MONTH (it throws an exception). Do I need to use Calendar ?

+7
java java-8 java-time truncate
source share
3 answers

One way is to manually set the day to the first month 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 LocalDate , which is possibly cleaner:

 LocalDate firstOfMonth = LocalDate.now(UTC).withDayOfMonth(1); long millis = firstOfMonth.atStartOfDay(UTC).toEpochSecond() * 1000; //or long millis = firstOfMonth.atStartOfDay(UTC).toInstant().toEpochMilli(); 
+10
source share

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

 date.with(TemporalAdjusters.firstDayOfMonth())).truncatedTo(ChronoUnit.DAYS); 
+10
source share

For an easy way to do this:

 Calendar cal = new GregorianCalendar(); System.out.println(cal.getTime()); cal.set(Calendar.DAY_OF_MONTH,1); System.out.println(cal.getTime()); cal.set(Calendar.HOUR_OF_DAY,0); System.out.println(cal.getTime()); cal.set(Calendar.MINUTE,0); System.out.println(cal.getTime()); cal.set(Calendar.SECOND,0); System.out.println(cal.getTime()); cal.set(Calendar.MILLISECOND,0); System.out.println(cal.getTime()); 

Output:

 Thu Jun 11 05:36:17 EDT 2015 Mon Jun 01 05:36:17 EDT 2015 Mon Jun 01 00:36:17 EDT 2015 Mon Jun 01 00:00:17 EDT 2015 Mon Jun 01 00:00:00 EDT 2015 Mon Jun 01 00:00:00 EDT 2015 
+1
source share

All Articles