6

new File(url).lastModified() returns a long equal to the number of milliseconds since the epoch, which is GMT-based.

What is a simple way to convert this to a String representing system-local date/time?

If you really need to see an attempt from me here it is but it's a terrible mess and it's wrong anyway:

LocalDateTime.ofEpochSecond(new File(url).lastModified()/1000,0,ZoneOffset.UTC).atZone(ZoneId.of("UTC")).format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG))

Beyond LocalDateTime I just have no idea how the time API works.

Tunaki
  • 132,869
  • 46
  • 340
  • 423
Museful
  • 6,711
  • 5
  • 42
  • 68

1 Answers1

6

To get the last modified time of a file, you should use Java NIO.2 API, which directly resolves your problem:

FileTime fileTime = Files.getLastModifiedTime(Paths.get(url));
System.out.println(fileTime); // will print date time in "YYYY-MM-DDThh:mm:ss[.s+]Z" format

If you want to access other properties (like last access time, creation time), you can read the basic attributes of a path with Files.readAttributes(path, BasicFileAttributes.class).

Tunaki
  • 132,869
  • 46
  • 340
  • 423
  • Is it possible to format a `FileTime` differently to that default, without first going back to square one using `FileTime::toMillis`? – Museful Oct 27 '15 at 14:25
  • 2
    @tennenrishin Yes, you can get an Instant with [`toInstant()`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/attribute/FileTime.html#toInstant--) and format it using [`DateTimeFormatter`](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html). – Tunaki Oct 27 '15 at 14:28
  • `DateTimeFormatter.ofPattern("uuuu-MMM-dd HH:mm:ss").format(fileTime.toInstant())` throws `java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: Year` for me. What am I doing wrong? – Museful Oct 29 '15 at 22:40
  • @tennenrishin Please refer to [this question](http://stackoverflow.com/q/13752031/1743880) to format a Instant property. – Tunaki Oct 30 '15 at 08:20