I am trying to get a specific time in UTC for "today".
Say 5pm UTC
Instant.now().truncatedTo(ChronoUnit.DAYS).plus(1, ChronoUnit.DAYS)
OR
Instant.now().plus(1, ChronoUnit.DAYS).truncatedTo(ChronoUnit.DAYS)
This i believe gets me to midnight current day. Do I just extend this
Instant.now().truncatedTo(ChronoUnit.DAYS).plus(1, ChronoUnit.DAYS).minus(7, ChronoUnit.HOURS);
Or is there a better way to do this.
Asked
Active
Viewed 160 times
1
-
Or better yet, the next time its 5pm UTC. – Pradyot Feb 09 '18 at 15:24
-
There is no guaranty to get “5pm” through arithmetic from an instant. – Holger Feb 09 '18 at 15:38
-
Thanks. Any other approach you suggest to get a specific UTC time for "today". – Pradyot Feb 09 '18 at 15:41
-
@Holger, `Instant` also supports `with(LocalTime)`, so it should not be very hard. – M. Prokhorov Feb 09 '18 at 15:46
-
My bad: Instant actually doesn't support that. For some reason, there is no support for `nano-of-day` chrono field, which is what LocalTime uses for representing itself as a single value. – M. Prokhorov Feb 09 '18 at 15:47
-
@M.Prokhorov: you can use `LocalDate.now().atTime(17, 0).toInstant(ZoneOffset.UTC)`; I never said, it was hard, only that you should not try to use *arithmetic on an instant*, as “5pm” does not necessarily imply “7 hours before midnight”… – Holger Feb 09 '18 at 15:50
-
@Holger, yes, that is true, adding or subtracting something to dates ignores a lot of details about them, so preferred solution to get some specific date-time is to construct it rather than compute. – M. Prokhorov Feb 09 '18 at 15:52
-
An `Instant` is conceptually just a point on the time line. Don’t think of it as being inherently UTC. Use `OffsetDateTime` for calculating the desired date and time in UTC and then convert to `Instant` using `OffsetDateTime.toInstant()`. – Ole V.V. Feb 09 '18 at 18:32
1 Answers
4
That would be something along these lines
ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
// this would be the today (might be in the past)
ZonedDateTime result = now.with(LocalTime.of(17, 0));
if (result.isBefore(now)) {
// This would be "next time it is 5 o-clock".
result = result.plusDays(1);
}
// if you really want an Instant out of it.
return result.toInstant();

M. Prokhorov
- 3,894
- 25
- 39