0

How to obtain UTC at Midnight Timestamp with java.time.Instant and ChronoUnit?

I am trying to get UTC at Midnight Timestamp in format. For example, if today were Feb 10 2017, then correct date: Fri Feb 10 00:00:00 UTC 2017 which is equal to timestamp: 1486684800000 (I want for current date and time).

I tried

Instant.now
Instant.now.getEpochSecond to pass in JSON it end up in error

Error :

"statusCode":400,"titleMessage":"Value not allowed","userMessage":"The date with time stamp 2,022 is not in UTC at midnight

Please suggest a solution

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • Is that so?? *`time stamp 2,022`* sounds like you accidentally passed the current year in JSON, but the code you showed doesn’t do that. – Ole V.V. Oct 21 '22 at 05:56
  • Do you want a date of your choice, for example Feb 10 2017, or do you want today in UTC? Also do you need seconds or milliseconds since the epoch? (The example value you mention, 1486684800000, is milliseconds, but your code gives seconds.) – Ole V.V. Oct 21 '22 at 06:03
  • 1
    In Java syntax: `LocalDate.of(2017, Month.FEBRUARY, 10).atStartOfDay(ZoneOffset.UTC).toEpochSecond()`. Gives 1 486 684 800. – Ole V.V. Oct 21 '22 at 06:04
  • @OleV.V. thank you. I want for current date and time. – RUDRA GANESH SUBBARAYULU Oct 21 '22 at 06:06
  • In that case use `LocalDate.now(ZoneOffset.UTC)` instead of `LocalDate.of(2017, Month.FEBRUARY, 10)` (or pass the time zone of your choice to `LocalDate.now()`). – Ole V.V. Oct 21 '22 at 06:08
  • Under the linked original questions avoid answers using `Date` or `Calendar`. Use the ones that use java.time, which are most of them. For UTC time prefer `OffsetDateTime` over `ZonedDateTime` (used in one answer where it was needed because of the time zone). Your question has been asked and answered with variations before, so you can search to find even more. – Ole V.V. Oct 21 '22 at 10:52
  • Someone upvoted this unclear and apparently poorly researched question. Opinions on question quality differ too. – Ole V.V. Oct 21 '22 at 10:59

1 Answers1

1

Truncate

You can lop off the less significant parts of a date-time value.

In Java syntax:

Instant
.now()
.truncatedTo( ChronoUnit.DAYS )
.toEpochMilli()
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • Thank you for providing the solution I just added .toEpochMilli it worked perfectly. import java.time.temporal.ChronoUnit; Instant.now().truncatedTo( ChronoUnit.DAYS ).toEpochMilli – RUDRA GANESH SUBBARAYULU Oct 21 '22 at 06:18