16

I have the time in milliseconds and I need to convert it to a ZonedDateTime object.

I have the following code

long m = System.currentTimeMillis();
LocalDateTime d = LocalDateTime.millsToLocalDateTime(m);

The line

LocalDateTime d = LocalDateTime.millsToLocalDateTime(m);

gives me a error saying methed millsToLocalDateTime is undefined for type LocalDateTime

Anish B.
  • 9,111
  • 3
  • 21
  • 41
Ted pottel
  • 6,869
  • 21
  • 75
  • 134

4 Answers4

22

ZonedDateTime and LocalDateTime are different.

If you need LocalDateTime, you can do it this way:

long m = ...;
Instant instant = Instant.ofEpochMilli(m);
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
xingbin
  • 27,410
  • 9
  • 53
  • 103
15

You can construct a ZonedDateTime from an instant (this uses the system zone ID):

//Instant is time-zone unaware, the below will convert to the given zone
ZonedDateTime zdt = ZonedDateTime.ofInstant(Instant.ofEpochMilli(m), 
                                ZoneId.systemDefault());

And if you need a LocalDateTime instance from that:

//And this date-time will be "local" to the above zone
LocalDateTime ldt = zdt.toLocalDateTime();
ernest_k
  • 44,416
  • 5
  • 53
  • 99
10

Whether you want a ZonedDateTime, LocalDateTime, OffsetDateTime, or LocalDate, the syntax is really the same, and all revolves around applying the milliseconds to an Instant first using Instant.ofEpochMilli(m).

long m = System.currentTimeMillis();

ZonedDateTime  zdt = ZonedDateTime.ofInstant(Instant.ofEpochMilli(m), ZoneId.systemDefault());
LocalDateTime  ldt = LocalDateTime.ofInstant(Instant.ofEpochMilli(m), ZoneId.systemDefault());
OffsetDateTime odt = OffsetDateTime.ofInstant(Instant.ofEpochMilli(m), ZoneId.systemDefault());
LocalDate      ld  = LocalDate.ofInstant(Instant.ofEpochMilli(m), ZoneId.systemDefault());

Printing them would produce something like this:

2018-08-21T12:47:11.991-04:00[America/New_York]
2018-08-21T12:47:11.991
2018-08-21T12:47:11.991-04:00
2018-08-21

Printing the Instant itself would produce:

2018-08-21T16:47:11.991Z
Andreas
  • 154,647
  • 11
  • 152
  • 247
2

You cannot create extension methods in Java. If you want to define a separate method for this create a Utility class:

class DateUtils{

    public static ZonedDateTime millsToLocalDateTime(long m){
        ZoneId zoneId = ZoneId.systemDefault();
        Instant instant = Instant.ofEpochSecond(m);
        ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, zoneId);
        return zonedDateTime;
    }
}

From your other class call

DateUtils.millsToLocalDateTime(89897987989L);
xtra
  • 1,957
  • 4
  • 22
  • 40