因为您没有格式化date
. 看例子
public static void main(String[] args){
Locale currentLocale = Locale.US;
DateFormat f = new SimpleDateFormat("EEE MMM dd HH:mm:ss zz yyyy", currentLocale);
Date date = null;
Date today;
try {
today = new Date();
String result = f.format(today);
System.out.println("Locale: " + currentLocale.toString());
System.out.println("Result: " + result);
date = f.parse("Tue Aug 23 20:00:03 PDT 2011");
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("---date----" + f.format(date));
}
将输出
Locale: en_US
Result: Tue Sep 25 19:12:38 EEST 2012
---date----Tue Aug 23 20:00:03 PDT 2011
现在,你有一些修改的代码
public static void main(String[] args){
Locale currentLocale = Locale.US;
DateFormat f = new SimpleDateFormat("EEE MMM dd HH:mm:ss zz yyyy", currentLocale);
DateFormat f2 = new SimpleDateFormat("EEE MMM dd HH:mm:ss zz yyyy", currentLocale);
Date date = null;
Date today;
try {
today = new Date();
String result = f.format(today);
System.out.println("Locale: " + currentLocale.toString());
System.out.println("Result: " + result);
date = f.parse("Tue Aug 23 20:00:03 PDT 2011");
System.out.println("---date----" + f.format(date));
System.out.println("---date----" + f2.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
}
输出到
Locale: en_US
Result: Tue Sep 25 20:42:10 EEST 2012
---date----Tue Aug 23 20:00:03 PDT 2011
---date----Wed Aug 24 06:00:03 EEST 2011
即使指定了模式,似乎SimpleDateFormat
也不关心时区。'z'
它在解析输入时设置时区。这就是我可以描述这种奇怪行为的方式。然后使用'z'
模式似乎已经过时并导致不可预测的结果。
所以设置TimeZone
将解决问题
f2.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));