Martinnj
Martinnj

Reputation: 619

File age in Java

I need to find the age of a file based on its name. Alle the files keep to a naming convention like this: DD-MM-YYYY.

I can make a program to come up with the filenames based on how many days/months has passed etc, using the modulus operator, but i can't seem to wrap my head around how to calculate the age from the name. Any tip is welcome.

Any codesamples/ -suggestions should preferable be in Java.

Regards Martin

Upvotes: 2

Views: 5900

Answers (2)

oliholz
oliholz

Reputation: 7507

if the last modified date is enough, you can use:

    File file = new File("C:/file.txt");
    Date date = new Date(file.lastModified());
    System.out.println(date);

Upvotes: 1

Mark Peters
Mark Peters

Reputation: 81074

You can use a DateFormat to parse a date as well as format one.

Untested:

String name = file.getName();
String datePortion = /*extract date portion*/;

DateFormat fmt = new SimpleDateFormat("dd-MM-yyyy");
Date fileDate = fmt.parse(datePortion);
long msBetweenDates = new Date().getTime() - fileDate.getTime();

How you extract the date portion depends on your file naming scheme, but it's probably as easy as:

String datePortion = name.replaceAll(".*((\\d)+-(\\d)+-(\\d)+).*", "$1");

Upvotes: 8

Related Questions