How to Convert FileTime to String with DateFormat

Converting FileTime to Date

Path path = Paths.get("C:\\Logs\\Application.evtx");
DateFormat df=new SimpleDateFormat("dd/MM/yy");
try {
    BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
    Date d1 = df.parse(df.format(attr.creationTime().toMillis()));
    System.out.println("File time  : " +d1);
} catch (Exception e) {
    System.out.println("oops error! " + e.getMessage());
}

use this code to convert


Just get the milliseconds since epoch from the FileTime.

String dateCreated = df.format(date.toMillis());
//                                 ^

Convert FileTime to millis by toMillis() method.

String file = "C:\\foobar\\example.docx";
Path filepath = Paths.get(file);
        BasicFileAttributes attr = Files.readAttributes(filepath, BasicFileAttributes.class);
        FileTime date = attr.creationTime();
        SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
        String dateCreated = df.format(date.toMillis());
        System.out.println(dateCreated);

Use this code to get formatted value.


In Java 8, you can convert the FileTime into ZonedDateTime before formatting it:

BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
long cTime = attr.creationTime().toMillis();
ZonedDateTime t = Instant.ofEpochMilli(cTime).atZone(ZoneId.of("UTC"));
String dateCreated = DateTimeFormatter.ofPattern("MM/dd/yyyy").format(t);
System.out.println(dateCreated);

which prints:

06/05/2018

Tags:

Datetime

Java

Nio