How to convert FileTime to String with DateFormat

I am trying to convert the creationTime attribute of a file to a string with the date format MM / dd / yyyy. I use Java nio to get the creationTime attribute, which is of type FileTime , but I just need the date from this FileTime as a string with the date format specified earlier. As long as I have ...

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

However, it throws an exception saying that it cannot format the FileTime date object as a date. FileTime seems to be output as 2015-01-30T17:30:57.081839Z , for example. What solution would you recommend to best solve this problem? Should I just use regex on this output or is there a more elegant solution?

+8
java
source share
3 answers

Just get milliseconds from an era from FileTime .

 String dateCreated = df.format(date.toMillis()); // ^ 
+8
source share

Convert FileTime to Milliscus using the 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 a formatted value.

+9
source share

Convert 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

+2
source share

All Articles