Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 BasicFileAttributes.creationTime() returning different hour value

Tags:

java

java-8

I have this code snippet using Java 8 to get the Creation Date Time of a specific file:

    Path path = Paths.get("D:\\SampleFile.txt");
    BasicFileAttributes attributes = null;
    try {
        attributes = Files.readAttributes(path, BasicFileAttributes.class);
        System.out.println("Creation Date Time: " + attributes.creationTime());
    } catch(IOException ioe) {
        ioe.printStackTrace();
    }

The real creation hour of the file I am using as an example differs by 6 hours from the one the above code snippet displays:
Real date time: 2017-02-05T10:34:28
This code time: 2017-02-05T16:34:28.247156Z

Does anybody know what is the reason of this difference and how to get the correct create date time value ?

Thank you in advance!

like image 954
Jose Mena Avatar asked Sep 10 '26 09:09

Jose Mena


1 Answers

The FileTime class assumes UTC as the default time zone for printing. If you want to print it in your system's time zone, you can convert it to a ZonedDateTime like this:

attributes.creationTime().toInstant().atZone(ZoneId.systemDefault())
like image 193
shmosel Avatar answered Sep 12 '26 23:09

shmosel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!