我按照以下代码在指定的日期时间和指定的时区创建一个日期对象。
注意:我没有为 jvm 设置任何时区;但是用不同的 linux 服务器时区测试这段代码。
String date = "20121225 10:00:00";
String timeZoneId = "Asia/Calcutta";
TimeZone timeZone = TimeZone.getTimeZone(timeZoneId);
DateFormat dateFormatLocal = new SimpleDateFormat("yyyyMMdd HH:mm:ss z");
//This date object is given time and given timezone
java.util.Date parsedDate = dateFormatLocal.parse(date + " "
+ timeZone.getDisplayName(false, TimeZone.SHORT));
if (timeZone.inDaylightTime(parsedDate)) {
// We need to re-parse because we don't know if the date
// is DST until it is parsed...
parsedDate = dateFormatLocal.parse(date + " "
+ timeZone.getDisplayName(true, TimeZone.SHORT));
}
现在 parsedDate 对象的行为有所不同
当我的 jvm 服务器在 IST 中运行时
parsedDate.getTime() -- 1356409800000
parsedDate.toString() -- 2012 年 12 月 25 日星期二 10:00:00
在 GMT --- 12/25/2012 04:30:00 GMT
当我的 jvm 服务器在 EST 中运行时
parsedDate.getTime() -- 1356422400000
parsedDate.toString() -- 2012 年美国东部时间 12 月 25 日星期二 03:00:00
格林威治标准时间 --- 12/25/2012 08:00:00 GMT
我的两个系统时间是同步的
2012 年美国东部时间 12 月 24 日星期一 10:30:04
2012 年 IST 12 月 24 日星期一 21:00:48
我希望在两台机器上得到相同的 GMT 时间。
这里出了什么问题?
最佳答案
我认为问题在于您正在尝试解析 IST,它具有不同的含义,具体取决于您的默认“位置”是什么。
Time Zone Abbreviation Zone Description Relative UTC
IST Irish Summer Time UTC+01
IST Israeli Standard Time UTC+02
IST Iran Standard Time UTC+0330
IST Indian Standard Time UTC+0530
如果您的位置是印度,它会按照您的预期对待 IST,但如果您使用美国,它会猜测不同的时区。
解决方案是不使用三个字母的时区并明确设置它们。
String date = "20121225 10:00:00";
String timeZoneId = "Asia/Calcutta";
TimeZone timeZone = TimeZone.getTimeZone(timeZoneId);
DateFormat dateFormatLocal = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
dateFormatLocal.setTimeZone(timeZone);
Date parsedDate = dateFormatLocal.parse(date);
关于java - SimpleDateFormat 在不同的时区 JVM 中表现不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14075373/