从昨天开始,我一直在玩日历、时区和转换。这件事把我都搞糊涂了。这是我的代码:
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
millis:1381091100000
Default Cal:Year:2013, Month:9, Date:6, Hour:4, Minutes:25, Seconds:0, AM_PM: +1
EST:年:2013,月:9,日期:6,小时:8,分钟:25,秒:0,AM_PM:+1
如您所见,我在 test2() 中使用了与从 test1() 获得的相同的毫秒。测试 1 中的 Hour 是预期的 4,而在 test2 中是 8!是什么导致了这个问题?
谢谢。