There are a couple of problems with what you're trying to do.
Firstly, "today" is not a well-defined concept for a Date
. Date
is basically just a wrapper around number of milliseconds since Unix epoch: the calendar date corresponding to that instant is different, depending upon which timezone you are in.
For instance, the instant represented by new Date(1469584693000)
was on 2016-07-27 in London; but it was on 2016-07-26 in NYC.
You can, of course, rely upon the JVM's default timezone, but this makes the behaviour of the code dependent upon the JVM's configuration.
Secondly, "midnight" isn't something that always exists: e.g. in the Asia/Gaza
timezone, daylight savings starts at midnight, meaning that the clock jumps from 23:59:59 on one day to 01:00:00 on the next (see Ideone demo). This is why the Java 8 time API has methods called atStartOfDay
, not atMidnight
.
So, you can put this together, in Java 8, to:
private static void some(final Date now, ZoneId zone) {
Instant instant = now.toInstant(); // Convert from old legacy class to modern java.time class.
ZonedDateTime zdt = instant.atZone(zone); // Apply a time zone to the UTC value.
LocalDate today = zdt.toLocalDate(); // Extract a date-only value, without time-of-day and without time zone.
ZonedDateTime startOfDayToday = today.atStartOfDay(zone); // Determine first moment of the day.
ZonedDateTime startOfDayTomorrow = today.plusDays(1).atStartOfDay(zone);
// ...
}
Of course, you can directly pass in the Instant
or ZonedDateTime
to the method; and you can use an explicit constant ZoneId
, e.g. ZoneId.of("UTC")
.