Getting the correct GMT format using DateFormat Object

Warz picture Warz · Jan 26, 2012 · Viewed 10.9k times · Source

If i have a File object how can i get the lastModified() date of this file in this GMT format: Mon, 23 Jun 2011 17:40:23 GMT.

For example, when i call the java method lastModified() on a file and use a DateFormat object to getDateTimeInstance(DateFormat.Long, DateFormat.Long) and also set the TimeZone to GMT, the file date displays in different format:

File fileE = new File("/Some/Path");
Date fileDate = new Date (fileE.lastModified());
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.Long, DateFormat.Long);
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("file date " + dateFormat.format(fileDate));

This prints in this format:

January 26, 2012 7:11:46 PM GMT

I feel like i am close to getting it in the format above and i am only missing the day. Do i have to use instead the SimpleDateFormat object?

Answer

jtahlborn picture jtahlborn · Jan 26, 2012

Yes, the DateFormat static instances will be locale specific. If you want a specific format, you should use SimpleDateFormat with the appropriate format pattern.

If you want to compare 2 file modified times to the second granularity, then just divide them both by 1000, e.g.:

long t1InSeconds = f1.lastModified() / 1000L;
long t2InSeconds = f2.lastModified() / 1000L;

// which one is sooner
if(t1InSeconds < t2InSeconds) {
  // f1 is older ...
}