Margherita
Margherita

Reputation: 158

creationTime without timestamp in Java

EDIT: I want to take a file's creation time but without timestamp. My code is:

Path path = Paths.get(selectedFile.toURI());
BasicFileAttributes attr;
attr = Files.readAttributes(path, BasicFileAttributes.class);
System.out.println("Creation date: " + attr.creationTime());

Output:

Creation date: 2013-07-25T13:52:23.043207Z

How can I do to have only: Creation date: 2013-07-25? When I use SimpleDateFormat, it return me an error: for example if I use (like I've seen in this forum):

Calendar c = GregorianCalendar.getInstance();
String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY", attr.creationTime);
System.out.println("duke: " +s);

java.lang.RuntimeException: java.lang.reflect.InvocationTargetException

Upvotes: 0

Views: 1278

Answers (3)

SubOptimal
SubOptimal

Reputation: 22973

If selectedFile is of type java.io.File you could do it like

long lastModifiedMillis = selectedFile.lastModified();
Date lastModifiedDate = new Date(lastModifiedMillis);
String s = String.format("Duke's Birthday: %1$tY-%1$tm-%1$td", lastModifiedDate);
System.out.println("duke: " + s);

Upvotes: 0

Saravana
Saravana

Reputation: 12817

creationTime returns FileTime. We can get the instance or mills from it.

FileTime ft = attr.creationTime();

convert to date

Instant ins = ft.toInstant();
LocalDateTime ldt = LocalDateTime.ofInstant(ins, ZoneId.systemDefault());
LocalDate ld = ldt.toLocalDate();

or

LocalDate.ofEpochDay(ft.toMillis());

Upvotes: 1

Nicolas Filotto
Nicolas Filotto

Reputation: 44965

What returns creationTime() is a FileTime which is not supported by a SimpleDateFormat that is why it fails, you need to convert it first to a java.util.Date thanks to the method toMillis() as next

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
System.out.printf(
    "Creation date: %s%n", format.format(new Date(attr.creationTime().toMillis()))
);

NB: It fails with a String format for the same reason (FileTime not supported).

Upvotes: 1

Related Questions