Ohad Benita
Ohad Benita

Reputation: 543

Getting the long value of the start of the first day and end of last day of a given month in a year

Given a month (for March 3, for September 9, etc) and a year (2018, etc) I want to be able to get the epoch time value of two exact time-dates :

  1. Midnight at the first day of the given month (start of day)
  2. 23:59:59 for the last day of the given month (end of day)

Thanks in advance

Upvotes: 1

Views: 68

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521194

For the last instant of the current month, you may simply subtract one second from the midnight of the start of the preceding month. Here is a Java 8 option:

LocalDate start = LocalDate.of(2018, 5, 1);
LocalDate end = LocalDate.of(2018, 6, 1);
ZoneId zoneId = ZoneId.systemDefault();
long e1 = start.atStartOfDay(zoneId).toEpochSecond();
long e2 = end.atStartOfDay(zoneId).toEpochSecond() - 1L;

Demo

Upvotes: 2

Related Questions