从昨天开始,我一直在玩日历,时区和转换。这件事让我感到困惑。这是我的代码:
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));
}
}
输出:
创建日期:Sun Oct 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,而在test2中它是8!造成这个问题的原因是什么? 感谢。
答案 0 :(得分:1)
您的“默认校准”会在您当地的时区打印时间:EDT(-4) 您的“EST”日历以UTC / GMT时区打印时间,因为“Americas / New_York”不正确(额外的“s”),它应该是“America / New_York”,因为它不正确,TimeZone.getTimeZone(...)返回UTC