1

I know how to use file.lastModified();. When I println that I get (for example): Sat Mar 17 09:24:33 GMT+01:00 2012. But is it possible that I only get the day, month and year as numbers, for example: 17 03 2012

Is their a way to do this, maybe a filter, or an other function to get last modified date in numbers?

Bigflow
  • 3,616
  • 5
  • 29
  • 52

4 Answers4

3

is file a java.io.File object?

lastModified should return time in milliseconds. You can create a Date object with the lastModified return value and the format the output with a SimpleDateFormat

    Date date = new Date(file.lastModified());
    System.out.println(date);

    SimpleDateFormat sdf = new SimpleDateFormat("d M y");
    System.out.println(sdf.format(date));
Ste
  • 141
  • 1
  • 8
2

You can use SimpleDateFormat class, i.e.

package com.example.file;

import java.io.File;
import java.text.SimpleDateFormat;

public class GetFileLastModifiedExample
{
    public static void main(String[] args)
    {   
    File file = new File("\\somefile.txt");

    System.out.println("Before Format : " + file.lastModified());

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

    System.out.println("After Format : " + sdf.format(file.lastModified()));
    }
}
Bigflow
  • 3,616
  • 5
  • 29
  • 52
Amit
  • 13,134
  • 17
  • 77
  • 148
  • the return value of [lastModified](http://docs.oracle.com/javase/1.4.2/docs/api/java/io/File.html#lastModified%28%29) is a long. – oers Mar 22 '12 at 08:49
  • had to change `SimpleDateFormat sdf = new SimpleDateFormat("DD/MM/YYYY");` to `SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");` After that it worked perfectly. – Bigflow Mar 22 '12 at 09:04
1

Try this,

long longDate = file.lastModified();        
Date date = new Date(longDate);
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
String newDate = formatter.format(date);
System.out.println("Formatted date " + newDate);
user370305
  • 108,599
  • 23
  • 164
  • 151
0

according to the documentation

File.lastModifed()

should return a long value representing the time the file was last modified, measured in milliseconds since the epoch. Yon can use the long value in conjunction with Calendar

    Calendar rightNow = Calendar.getInstance()
    rightNow.setTimeInMillis(longValue)

and use rightNow.get(...)

to retrive day, month and year

Blackbelt
  • 156,034
  • 29
  • 297
  • 305