Getting the correct GMT format using DateFormat Object

六眼飞鱼酱① 提交于 2019-12-11 01:38:39

问题


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


来源:https://stackoverflow.com/questions/9024274/getting-the-correct-gmt-format-using-dateformat-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!