37

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

1
  • Reopened, because this question is about the conversion to java.util.Date.
    – Daniel
    Mar 27, 2018 at 20:23

4 Answers 4

53
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.

3
  • 4
    When using java.nio.file.attribute.FileTime, toMillis() has to be called
    – koppor
    Feb 5, 2015 at 16:19
  • 1
    lastModified() returns the milliseconds since 1970-01-01 using what timezone? I have an issue sending the date to a javascript running on the browser, and the date is one day greater than the server date.
    – ps0604
    Aug 15, 2018 at 22:17
  • @ps0604: I believe in the "current" timezone, which can be found with System.getProperty("user.timezone")
    – Daniel
    Aug 17, 2018 at 9:50
18

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()) 
);
6

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.

2
  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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.