Java: Incorrect time zone in Files.getLastModifiedTime

Viewed 922

I am trying to print out the last modified time of a file. Somehow, the timestamp returned is incorrect and different from the system time.

Files.getLastModifiedTime(Paths.get(directory, filename))

which prints 2019-01-14T11:48:47.312493Z

System time is in fact:

LocalDateTime.now()  <- 2019-01-14T19:48:50.495242600

How can I overcome this problem and make getLastModifiedTime returns the time in my local timezone?

2 Answers

LocalDateTime is, as the name says, the local date and time. It depends on the timezone configured on the machine. The machine probably runs in UTC+8. To get a timezone-less datetime, like getLastModifiedTime() returns, use Instant.now() instead of LocalDateTime.now().

Alternatively you can convert the Instant returned by getLastModifiedTime(...).toInstant() to your local date time:

Instant modified = Files
    .getLastModifiedTime(Paths.get(directory, filename))
    .toInstant();
LocalDateTime modifiedDateTime = modified
    .atZone(ZoneId.systemDefault())
    .toLocalDateTime();

where ZoneId.systemDefault() is the system's default configured timezone. You could also use a fixed timezone like ZoneId.of("CST") for China Standard Time for example. But I strongly recommend to always work with Instant where possible, because then you cannot accidentially compare datetimes from different timestamps, and avoid errors due to different environments the code runs on.

Seems FileTime#toString() returns datetime string is in UTC, here is a piece of it's source code:

ldt = LocalDateTime.ofEpochSecond(lo - SECONDS_0000_TO_1970, nanos, ZoneOffset.UTC);

You can get the Instant from FileTime then convert it to LocalDateTime with system time zone:

FileTime fileTime = Files.getLastModifiedTime(Paths.get(directory, filename));
LocalDateTime localDateTime = LocalDateTime.ofInstant(fileTime.toInstant(), ZoneId.systemDefault());
Related