Java 从一个区域到另一个区域的隐蔽日期时间
这是我之前的一个问题的延续,我无法解析现在解析的日期。在下面的代码中,我有一个日期字符串,我知道日期字符串的时区,即使字符串本身不包含它。然后我需要把日期转换成东部时间时区Java 从一个区域到另一个区域的隐蔽日期时间,java,jodatime,Java,Jodatime,这是我之前的一个问题的延续,我无法解析现在解析的日期。在下面的代码中,我有一个日期字符串,我知道日期字符串的时区,即使字符串本身不包含它。然后我需要把日期转换成东部时间时区 String clientTimeZone = "CST6CDT"; String value = "Dec 29 2014 11:36PM"; value=StringUtils.replace(value, " ", " "); DateTimeForm
String clientTimeZone = "CST6CDT";
String value = "Dec 29 2014 11:36PM";
value=StringUtils.replace(value, " ", " ");
DateTimeFormatter df = DateTimeFormat.forPattern("MMM dd yyyy hh:mma").withZone(DateTimeZone.forID(clientTimeZone));
DateTime temp = df.parseDateTime(value);
System.out.println(temp.getZone().getID());
Timestamp ts1 = new Timestamp(temp.getMillis());
DateTime date = temp.withZoneRetainFields(DateTimeZone.forID("EST"));//withZone(DateTimeZone.forID("EST"));
Timestamp ts = new Timestamp(date.getMillis());
System.out.println(ts1+"="+ts);
当我运行代码时,我希望ts1保持不变,ts运行1小时。但我不明白,我的情绪正在下降。我认为EST比CST早一个小时,所以如果CST是11,那么EST应该是12。此外,似乎还有大约11个半小时的时间被抵消。任何关于我遗漏什么的线索
2014-12-30 11:06:00.0=2014-12-30 10:06:00.0
我认为下面的代码将帮助您
String clientTimeZone = "CST6CDT";
String toStimeZone = "EST";
String value = "Dec 29 2014 11:36PM";
TimeZone fromTimeZone = TimeZone.getTimeZone(clientTimeZone);
TimeZone toTimeZone = TimeZone.getTimeZone(toStimeZone);
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(fromTimeZone);
SimpleDateFormat sf = new SimpleDateFormat("MMM dd yyyy KK:mma");
Date date = sf.parse(value);
calendar.setTime(date);
System.out.println(date);
calendar.add(Calendar.MILLISECOND, fromTimeZone.getRawOffset() * -1);
if (fromTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, calendar.getTimeZone().getDSTSavings() * -1);
}
calendar.add(Calendar.MILLISECOND, toTimeZone.getRawOffset());
if (toTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, toTimeZone.getDSTSavings());
}
System.out.println(calendar.getTime());
复制自:该方法保留时区CST=UTC-06中的字段,因此您的本地时间戳为LocalDateTime,但将其与不同的时区EST=UTC-05组合,后者在偏移量上提前一小时,并产生不同的瞬间。你应该这样解释:同一个当地时间在纽约比芝加哥早一个小时
规则是减去正偏移量,然后添加负偏移量,以便使实例的时间戳表示与UTC偏移量的标准化具有可比性
或者:可能您不希望这样做,但希望保留即时字段而不是本地字段。在这种情况下,您必须使用该方法
旁注:实际上,您比较了由变量temp和date表示的实例,最后使用默认时区在JDBC转义格式解释中打印这些实例-您隐式使用Timestamp.toString。为此,我建议使用专用的即时格式化程序,或者更简单地使用偏移量:
System.out.println(temp.toInstant() + " = " + date.toInstant());