I have a spring boot backend and I want to publish news at 9am UTC+1 everyday.
I would like to get a java.time.Instant
for:
Depending on if we 9am, how can I do it reliably for all my clients?
You can use OffsetDateTime
like this:
LocalTime targetTime = LocalTime.of(9, 0);
OffsetDateTime dateTime = OffsetDateTime.now(ZoneOffset.ofHours(1));
if (dateTime.toLocalTime().compareTo(targetTime) >= 0)
dateTime = dateTime.plusDays(1);
Instant instant = dateTime.with(targetTime).toInstant();
System.out.println(instant);
Output (executed at 2020-03-17T14:47+01:00)
2020-03-18T08:00:00Z
Change the >=
to >
if exactly 9 AM should stay as today.
After clarifying some misunderstandings, the answer was adjusted to use the default time zone of the client and return an Instant
.
That means, you can use a ZonedDateTime
with the system zone for this, have a look at the following method and its comments:
public static Instant determineNextNewsRelease() {
// get the current time using the default time zone of the client
ZonedDateTime now = ZonedDateTime.now(ZoneId.systemDefault());
// get 9 AM using the same day/date
ZonedDateTime nineAM = now.with(LocalTime.of(9, 0));
// and check if now is before nineAM
if (now.isBefore(nineAM)) {
return nineAM.toInstant();
} else {
return nineAM.plusDays(1).toInstant();
}
}
Use the method like this:
public static void main(String[] args) {
Instant nextNewsRelease = determineNextNewsRelease();
// and print the result
System.out.println("Next news will be released at "
+ nextNewsRelease.toEpochMilli() + " ("
+ ZonedDateTime.ofInstant(nextNewsRelease, ZoneId.systemDefault())
+ ")");
}
The result printed is
Next news will be released at 1584518400000 (2020-03-18T09:00+01:00[Europe/Berlin])
Try it...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.