0

I'm using java 8 and i have a method that accepts a date in long format parameter and returns a date in LocalDateTime from java.time.LocalDateTime library.

Before with java versions < 8, I used java.util.Date but now I need to use the java.time.LocalDateTime but I can't find documentation on how to convert from long value to LocalDateTime.

Before:

public Date setDate (long ldate){

  Date newDate = new Date(ldate);

  return newDate;
}

Now:

public LocalDateTime setDate(long ldate){

  LocalDateTime newDate;

  //{convert from long to LocalDateTime}

  return newDate
}

Thanks for your help!

  • @ernest_k i think this might be what i'm looking for, will you please explain what is the Epoch time? – Edward Kolta May 06 '19 at 19:34
  • Check this wikipedia page: https://en.wikipedia.org/wiki/Unix_time (in your case, `ldate` is the number of milliseconds since Epoch) – ernest_k May 06 '19 at 19:38
  • `LocalDateTime` is exactly the wrong class for this. Read its class JavaDoc. For a moment, use `Instant`, `OffsetDateTime`, or `ZonedDateTime`. – Basil Bourque May 06 '19 at 22:35

1 Answers1

-1

You can implement the method like this how LocalDateTime:

public LocalDateTime setDate(long ldate){

        Date dateLong = new Date(ldate);    
        Instant instant = dateLong.toInstant();
        ZoneId defaultZoneId = ZoneId.systemDefault();

        LocalDateTime localDateTime = instant.atZone(defaultZoneId).toLocalDateTime();
        return localDateTime;
}

  • 1
    There is no need to mix the terrible legacy class `Date` with the modern *java.time* classes. See the `Instant.ofEpoch…` methods. – Basil Bourque May 08 '19 at 01:32
  • The `LocalDateTime` is the wrong class here. That class discards the valuable time zone information. Use `ZonedDateTime` instead. – Basil Bourque May 08 '19 at 01:33