Getting the correct GMT format using DateFormat Ob

2019-07-11 21:19发布

问题:

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?

回答1:

Use the SimpleDateFormat with the pattern as follows:

DateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss z");

Update:

Date d1 = new Date(file1.lastModified());
Date d2 = new Date(file2.lastModified());

You can compare them as follows:

d1.compareTo(d2);
d1.before(d2);
d1.after(d2);

Why do you want to compare them at seconds granularity?

If you want to get the difference in seconds:

int diffInSeconds = (int) (d1.getTime() - d2.getTime()) / 1000;


回答2:

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