我转换时区的值为UTC-1,.,UTC-12,然而,当打印它的日期/时间时,它没有显示转换的时区。
final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC-1"));
System.out.println(dateFormat.format(actualDate)); // actualDate showing older time zone and not according to UTC-1而不是使用UTC-1,UTC-2…等等,如果我使用“America/New York”,它将显示正确的时区。
final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
dateFormat.setTimeZone(TimeZone.getTimeZone("America/New_York"));
System.out.println(dateFormat.format(actualDate)); // actualDate showing updated time zone EDT如果我遗漏了什么,请建议,因为我想使用UTC-1、UTC-2、...UTC+1等值。
发布于 2019-12-30 07:21:52
TL;DR:支持"UTC"前缀,使用ZoneId__。见答案的结尾。
如果阅读了文档(即TimeZone.getTimeZone(String ID)的javadoc ),它会说:
获取给定ID的
TimeZone。
参数:
ID - TimeZone的ID,或者是一个缩写,比如"PST",一个全名,比如“America/洛杉矶”,或者是一个定制的ID,比如"GMT-8:00“。请注意,对缩写的支持仅限于JDK1.1.x兼容性,应该使用全名。
返回:
如果无法理解给定的ID,则指定的TimeZone,或 GMT区域。
所以让我们来测试一下:
System.out.println(TimeZone.getTimeZone("UTC-1"));输出
sun.util.calendar.ZoneInfo[id="GMT",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]javadoc确实说过GMT-8:00是有效的,所以让我们测试一下:
System.out.println(TimeZone.getTimeZone("GMT-1"));输出
sun.util.calendar.ZoneInfo[id="GMT-01:00",offset=-3600000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]如果您读取了TimeZone本身的javadoc:
如果您想要的时区不是由一个受支持的ID表示的,那么可以指定一个自定义时区ID来生成TimeZone。自定义时区ID的语法为:
CustomID:格林尼治时间:分钟格林尼治时间:格林尼治时间标志:+-小时:数字数字分钟:数字数字:0 1 2 3 4 5 6 7 8 9之一
如您所见,自定义时区必须从GMT开始。
新的Java8TimeAPI支持UTC-1。
System.out.println(ZoneId.of("UTC-1"));输出
UTC-01:00这意味着,如果您的actualDate值是java.util.Date,则可以将其格式化如下:
Date actualDate = new Date();
System.out.println(actualDate);
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss z")
.withZone(ZoneId.of("UTC-1"));
System.out.println(dateFormat.format(actualDate.toInstant()));输出
Mon Dec 30 02:29:41 EST 2019
2019-12-30 06:29:41 UTC-01:00如您所见,时间已调整为UTC-01:00时区。
https://stackoverflow.com/questions/59525878
复制相似问题