我正在尝试将GMT+2时间转换为GMT-4 time.But,我在如何实现从一个时区时间到其他时区时间的转换方面遇到了意外的results.Help me。
originTime = "2015-08-15T10:25:00";
SimpleDateFormat converter = new SimpleDateFormat("yyyy-MM-dd hh:mm");
converter.setTimeZone(TimeZone.getTimeZone("GMT-4"));
GregorianCalendar oc = originTime.toGregorianCalendar();
String OriginStart=converter.format(oc.getTime()); 如果是GMT-4,上面的代码必须给出比给定时间更短的originStart时间。但是我得到了比给定时间更长的OriginStart时间。
发布于 2015-04-09 20:47:25
假设timzone字符串是有效的(因为我还没有尝试过),尝试如下所示
String originTime = "2015-08-15 10:25";
SimpleDateFormat converter = new SimpleDateFormat("yyyy-MM-dd hh:mm");
converter.setTimeZone(TimeZone.getTimeZone("GMT+10"));
Date date = converter.parse (originTime);
converter.setTimeZone(TimeZone.getTimeZone("GMT-4"));
String OriginStart=converter.format(date); 发布于 2015-04-11 07:06:40
填充零
ISO 8601标准要求偏移小时数具有填充零。所以使用-04而不是-4。
顺便说一句,java.time的原始版本有一个错误,它无法解析没有菜单的小时偏移值。因此,在这种情况下,请使用-04:00而不是-04。
指定时区
时区包括有关夏令时(DST)和其他异常的规则,包括过去、现在和将来。
.Calendar和SimpleDateFormat类是出了名的麻烦和混乱。避开他们。
取而代之的是使用Joda-Time或Java8内置的新java.time package (灵感来自Joda-Time)。
ISO 8601
ISO 8601标准为日期-时间值定义了合理、明确的字符串格式。您的输入字符串格式符合此wise标准。
示例
定义输入,格式为ISO 8601,与UTC没有任何偏移量。
String input = "2015-08-15T10:25:00";如果输入和输出,请指定时区。
DateTimeZone zoneInput = DateTimeZone.forOffsetHours( 2 );
// DateTimeZone zoneInput = DateTimeZone.forID( "Africa/Bujumbura" ); // Preferably the specific time zone name.
DateTimeZone zoneTarget = DateTimeZone.forOffsetHours( -4 );
// DateTimeZone zoneTarget = DateTimeZone.forID( "America/Martinique" ); // Preferably the specific time zone name.在分配时区时解析字符串。然后调整时区。
DateTime dateTimeOriginal = new DateTime( input , zoneInput );
DateTime dateTimeTarget = dateTimeOriginal.withZone( zoneTarget );转储到控制台。
System.out.println( "zoneInput / zoneTarget : " + zoneInput + " / " + zoneTarget );
System.out.println( "dateTimeOriginal : " + dateTimeOriginal );
System.out.println( "dateTimeTarget : " + dateTimeTarget );运行时。
zoneInput / zoneTarget : +02:00 / -04:00
dateTimeOriginal : 2015-08-15T10:25:00.000+02:00
dateTimeTarget : 2015-08-15T04:25:00.000-04:00https://stackoverflow.com/questions/29538425
复制相似问题