Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert FileTime to String with DateFormat

Tags:

java

datetime

nio

I'm attempting to convert the creationTime attribute of a file to a string with a date format of MM/dd/yyyy. I am using Java nio to obtain the the creationTime attribute, which is of FileTime type, but I just want the date from this FileTime as a string with the date format specified previously. So far 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 it cannot format the FileTime date object as a Date. FileTime seems to output in form of 2015-01-30T17:30:57.081839Z for example. What solution would you recommend to best solve this? Should I just use regex on that output or is there a more elegant solution?

like image 452
user2150250 Avatar asked Feb 03 '15 17:02

user2150250


1 Answers

Just get the milliseconds since epoch from the FileTime.

String dateCreated = df.format(date.toMillis());
//                                 ^
like image 159
Sotirios Delimanolis Avatar answered Oct 15 '22 03:10

Sotirios Delimanolis