-2

I have receive a timestamp in request as Integer format

target_time = 1728962183

Then I want to use it to compare with LocalDateTime.now() to decide the code flow.

Exp:

if(target_time < LocalDateTime.now()) { // perform some action } 

How do I convert the Integer timestamp to Date format?

2

1 Answer 1

1

tl;dr

Instant .ofEpochSecond ( 1_728_962_183L ) .isBefore( Instant.now() ) 

Epoch reference

If you know that number to be a count of whole seconds since the epoch reference of first moment of 1970 in UTC (1970-01-01T00:00Z), then convert to an Instant.

Instant

long count = 1_728_962_183L; Instant instant = Instant.ofEpochSecond ( count ); 

instant.toString() = 2024-10-15T03:16:23Z

Compare to the current moment to see if that moment has passed.

boolean isPast = instant.isBefore( Instant.now() ) ; 

LocalDateTime is the wrong class

You asked:

compare with LocalDateTime.now(

The LocalDateTime class represents a date with time-of-day, but lacks the context of a time zone or offset-from-UTC. Without that context, a date-with-time is ambiguous. We don't know if that was the date and time in Tokyo Japan, or in Toulouse France, or in Toledo Ohio US – three very different moments, several hours apart.

So the LocalDateTime class cannot represent a moment, is not a point on the timeline. So it makes no sense to compare a LocalDateTime to a moment.

Represent a moment

Three classes in java.time represent a moment. They provide three different ways to look at a moment.

  • Instant
    A moment as seen in UTC, that is, with an offset of zero hours-minutes-seconds from the temporal meridian of UTC. This class is the basic building-block of java.time framework.
  • OffsetDateTime
    A moment as seen through an offset, some number of hours-minutes-seconds ahead or behind the temporal meridian of UTC.
  • ZonedDateTime
    A moment as seen through a particular time zone.

An offset is merely a number of hours-minutes-seconds. A time zone is much more. A time zone is a named history of the past, present, and future changes to the offset used by the people of a particular region, as decided by their politicians.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.