1

I'd like to get the last modified date in my computers timezone (same that I see in the windows file explorer)

System.out.println(myFile.lastModified()); // I get UTC
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
lipilocid
  • 87
  • 8
  • 1
    `"same that I see "`.. how do we can know what do you see? Why don't give us the example and let us determine by ourselves? Please, include this information to your question. :)) – Nikolas Charalambidis Jun 07 '18 at 08:19
  • 1
    Please put a [Minimal, Complete, and Verifiable](https://stackoverflow.com/help/mcve) example in the question itself. – Rajesh Pandya Jun 07 '18 at 08:25
  • Possible duplicate of [java convert milliseconds to time format](https://stackoverflow.com/questions/4142313/java-convert-milliseconds-to-time-format). There are many other similar questions and answers, please use your search engine. – Ole V.V. Jun 07 '18 at 08:26

2 Answers2

4

From documentation myFile.lastModified()

Returns: A long value representing the time the file was last modified, measured in milliseconds since the epoch (00:00:00 GMT, January 1, 1970), or 0L if the file does not exist or if an I/O error occurs

So you need to convert it to a date, if you are using Java 8+, you can use java.time API like so :

LocalDateTime date = LocalDateTime.ofInstant(
        Instant.ofEpochMilli(myFile.lastModified()), ZoneId.systemDefault()
);

System.out.println(date);//example result : 2018-06-06T15:05:19.113

If you want more precision you can use :

File myFile = new File("pathname");
Long timeMs = myFile.lastModified();
if (timeMs != 0) {
    LocalDateTime date = LocalDateTime.ofInstant(
            Instant.ofEpochMilli(myFile.lastModified()), ZoneId.systemDefault()
    );
    System.out.println(date);
}else{
    System.out.println("File not exist!");
}
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
1

You can simply use a ZonedDateTime object and apply the system's default time offset to it.

ZonedDateTime zt = ZonedDateTime.ofInstant(Instant.ofEpochMilli(myFile.lastModified()), ZoneId.systemDefault());

You can then simply print out this object or work further with it.

Ben
  • 1,665
  • 1
  • 11
  • 22