Convert DateTime to unixtime

2

Good morning, someone can help me? I have a Java application and I need to do a conversion .. In which is the localDate for unixtime .. How can I do this?

This is my localDate:

for (Telemetry telemetry : listTelemetry) {


        telemetry.getInstant();
}

Entity:

public LocalDateTime getInstant() {
    return instant;
}
    
asked by anonymous 27.10.2015 / 13:17

1 answer

0

You can use it as well

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

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

To use the LocalDateTime object you can use 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 at link

    
27.10.2015 / 14:16