London
London

Reputation: 15274

How to convert the file last modified timestamp to a date?

How do I convert File#lastModified() to a real date? The format is not really important.

Upvotes: 37

Views: 80116

Answers (4)

Daniel
Daniel

Reputation: 28074

Date d = new Date(file.lastModified());

lastModified() returns the milliseconds since 1970-01-01, and the Date class stores its time also in the same way. The Date(long) constructor takes these milliseconds, and initializes the Date with it.

Upvotes: 53

Shankar Kumar Thakur
Shankar Kumar Thakur

Reputation: 181

Just you use the SimpleDateFormat class to convert long to date. Only you execute code:

new SimpleDateFormat("dd-MM-yyyy HH-mm-ss").format(
    new Date(new File(filename).lastModified()) 
);

Upvotes: 18

Bozho
Bozho

Reputation: 597076

  1. Get the last modified timestamp, as described in the duplicate of your question

  2. Create a new Date object, or Calendar object. new Date(timestamp). Or Calendar.getInstance() and then call setTimeInMillis(timestamp). As the name suggests, the timestamp is actually a number of milliseconds (since Jan 1st 1970)

  3. You can then format the date via java.text.SimpleDateFormat

Upvotes: 2

iluxa
iluxa

Reputation: 6969

What you get is a long number representing the number of millis elapsed from Jan 1st, 1970. That's the standard way of representing dates.

try this:

java.util.Date myDate = new java.util.Date(theFile.lastModified());

and now you have a Date object at hand.

You can use SimpleDateFormat to print that date in a cuter way.

Upvotes: 6

Related Questions