从昨天开始,我一直在玩日历、时区和转换。这件事让我都感到困惑。这是我的代码:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
class Dates {
public static void main(String[] args) {
test1();
test2();
}
private static void test1() {
String dateString = "2013-10-06T16:25";
String pattern = "yyyy-MM-dd'T'HH:mm";
SimpleDateFormat dtf = new SimpleDateFormat(pattern);
long mil;
Date date;
try {
date = dtf.parse(dateString);
mil = date.getTime();
System.out.println("Create date:" + date);
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(mil);
System.out.println ("millis:"+ mil);
printCal ("Default Cal:", cal);
} catch (ParseException ex) {
Logger.getLogger(Dates.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static void test2() {
// TODO Auto-generated method stub
long ms = 1381091100000L;
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Americas/New_York"));
cal.setTimeInMillis(ms);
printCal ("EST: ", cal);
}
private static void printCal(String str, Calendar cal) {
// TODO Auto-generated method stub
System.out.println(str+"Year:" + cal.get(Calendar.YEAR) + ", Month:"
+ cal.get(Calendar.MONTH) + ", Date:"
+ cal.get(Calendar.DATE) + ", Hour:"
+ cal.get(Calendar.HOUR) + ", Minutes:"
+ cal.get(Calendar.MINUTE) + ", Seconds:"
+ cal.get(Calendar.SECOND) + ", AM_PM: +"+ cal.get(Calendar.AM));
}
}
输出:
发布日期:周日 十月 06 16:25:00 EDT 2013
毫秒:1381091100000
默认校准:年份:2013, 月份:9, 日期:6, 小时:4, 分钟:25, 秒:0, AM_PM: +1
EST: 年份:2013, 月份:9, 日期:6, 小时:8, 分钟:25, 秒:0, AM_PM: +1
如您所见,我在test2()中使用了与test1()相同的millis。测试 1 中的小时是预期的 4,而在测试 2 中是 8!是什么导致了这个问题?
谢谢。
您的"默认校准"以您的本地时区打印时间:EDT (-4)您的"EST"日历以UTC/GMT时区打印时间,因为"Americas/New_York"不正确(额外的"s"),它应该是"America/New_York",因为它不正确,TimeZone.getTimeZone(...)返回UTC