32

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?

Community
  • 1
  • 1
EnverOsmanov
  • 625
  • 1
  • 7
  • 17

4 Answers4

45

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

date.with(TemporalAdjusters.firstDayOfMonth()).truncatedTo(ChronoUnit.DAYS);
Klesun
  • 12,280
  • 5
  • 59
  • 52
Simon
  • 6,293
  • 2
  • 28
  • 34
28

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;
//or
long millis = firstOfMonth.atStartOfDay(UTC).toInstant().toEpochMilli();
Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
assylias
  • 321,522
  • 82
  • 660
  • 783
0

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();
-1

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
MozenRath
  • 9,652
  • 13
  • 61
  • 104
  • Uh this not simple, in fact things like that were the whole reason of new Java 8 Dates API. – Rafael Oct 20 '20 at 14:53
  • Interesting. This answer serves as a fine example of how java date manipulation code used to be written. And while perhaps looking rather straight-forward, it's not exactly elegant. So please read and learn from the other answers, and never write code like this again. – Stephan Henningsen Nov 28 '20 at 19:11