0

I am trying to get a time duration b/w the 00:00:00 HRS of current day and Instant.now()

Instant startTime = Instant.now().minus(Duration.ofMinutes(????))
Instant endTime = Instant.now();

What should I pass here to get the 00:00:00 Hours of current day?

Shibankar
  • 806
  • 3
  • 16
  • 40
  • 1
    Do you have to use `Instant`? Why not `Date` or `Calendar` ? – Vucko Jun 17 '20 at 10:22
  • mean are you trying to get time passed since today 00 AM? – silentsudo Jun 17 '20 at 10:23
  • You can do something like this LocalDate.now().atStartOfDay().toInstant(ZoneOffset.UTC) – b.GHILAS Jun 17 '20 at 10:24
  • Isn't the time between 00:00 and now just the current time? – DobromirM Jun 17 '20 at 10:27
  • @Vucko Yes, I have to use Instant – Shibankar Jun 17 '20 at 10:42
  • @DobromirM Not always, if there are time changes due to DST, they may be not the same. – MC Emperor Jun 17 '20 at 11:04
  • 1
    @Vucko Why not `Date` or `Calendar` — because they're obsolete, and also terribly troublesome. See also [What's wrong with Java Date & Time API?](https://stackoverflow.com/questions/1969442/whats-wrong-with-java-date-time-api) – MC Emperor Jun 17 '20 at 11:07
  • @Vucko [Why do we need a new date and time library?](https://www.oracle.com/technical-resources/articles/java/jf14-date-time.html) [Still using java.util.Date? Don’t!](https://programminghints.com/2017/05/still-using-java-util-date-dont/) – Ole V.V. Jun 17 '20 at 16:20
  • @Shibankar hen you need to tell us: 00:00:00 in which time zone? At least once per hour, sometimes several times per hour, it’s 00:00:00 in some time zone. – Ole V.V. Jun 17 '20 at 16:22

1 Answers1

4

An instant is a moment on the timeline. It depends whether you want to take timezones and DST changes into consideration or not.

If you don't care about timezone or DST, you could do

LocalDateTime now = LocalDateTime.now();
ChronoUnit.HOURS.between(now.toLocalDate().atStartOfDay(), now);

The returned long is the number of hours between midnight and the current time. This will be by far in most cases the hour number as displayed by your wall clock. Also note that this code snippet does not make use of Instant, since and instant does not know about the human representation of time, like 00:00:00 midnight.

If you do care about timezone or DST, then you need to specify your timezone in order to adjust for time changes. For instance, within Europe/Amsterdam timezone, on March 29, 2020 at 02:00 wall clock time, the clock skips 1 hour because of DST (called "zomertijd" or "summer time"), so if now is 14:39 wall clock time, the number of hours since midnight is not 14 but 13.

You can then do something like this:

ZoneId zone = ...
Instant now = Instant.now();
Instant midnight = now.atZone(zone).toLocalDate().atStartOfDay(zone).toInstant();
long result = ChronoUnit.MINUTES.between(midnight, now);

Make sure you query now() once, otherwise you may get wrong results in corner cases.

MC Emperor
  • 22,334
  • 15
  • 80
  • 130