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?
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?
For a simple way to do it:
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());
The output is:
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
I had same problem of course in working with instants, then following code solved my problem:
Instant instant = Instant.ofEpochSecond(longTimestamp);
instant = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault())
.with(TemporalAdjusters.firstDayOfMonth())
.truncatedTo(ChronoUnit.DAYS).toInstant();
This is what java.time.temporal.TemporalAdjusters
are for.
date.with(TemporalAdjusters.firstDayOfMonth()).truncatedTo(ChronoUnit.DAYS);
One way would be to manually set the day to the first of the month:
Or an alternative with a
LocalDate
, which is maybe cleaner: