Convert Datetime to unixtime

Asked

Viewed 59 times

2

Good morning guys, can anyone help me? I have a Java application and I need to do a conversion.. Where is localDate for unixtime.. How can I do that?

This is my localDate:

for (Telemetry telemetry : listTelemetry) {


        telemetry.getInstant();
}

Entity:

public LocalDateTime getInstant() {
    return instant;
}

1 answer

0

You can use it like this

public Long getInstant() {
    Date date = new Date();
    return date.getTime();
}

Note the type of data returned which in the case of getTime is a Long representing a Timestamp. Date will return an object containing the Current System Date and Time as defined by the Operating System.

To use the Localdatetime object you can use it like this:

    LocalDateTime d = LocalDateTime.now(); // momento atual
    // Use ZoneId.systemDefault() para pegar o ZoneId do SO
    Date date2 = Date.from(d.atZone(ZoneId.systemDefault()).toInstant());
    // ou defina qual ZoneId deseja
    Date date2 = Date.from(d.atZone(ZoneId.of("America/Sao_Paulo")).toInstant());
    System.out.println(date2.getTime());

If you want to return the Localdatetime object from a database information use something like this

String str = "1986-04-08 12:30";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime dateTime2 = LocalDateTime.parse(str, formatter);
Date date3 = Date.from(dateTime2.atZone(ZoneId.of("Europe/London")).toInstant());
System.out.println(date3.getTime());

See the code working on https://ideone.com/oivrsH

  • more inside that my getInstant I have a Localdatetime, I need to work with that value that is coming from my bank and then turn it into Unix timestamp.. how can I do this?

  • The return of the method needs to be Localdatetime as suggested by the signature of your method? If so, who will receive the conversion.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.