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?
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
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
To summarise:
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.toMillis());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.