2017-03-22 39 views
0

我想从给定的时区获得当前时间,可以像“IST”或“印度标准时间”等。 当输入为“印度标准时间”或“协调世界时”时,我无法获得时间。它只适用于“IST”或“UTC”或“EST”等。 我已经尝试过Joda-Time和SimpleDateFormat。如何从java中给定的时区名称获取当前时间?

SimpleDateFormat sd = new SimpleDateFormat(
      "yyyy.MM.dd G 'at' HH:mm:ss z"); 
Date date = new Date(); 
sd.setTimeZone(TimeZone.getTimeZone("IST")); 
System.out.println(sd.format(date)); 



DateTime now = new DateTime(); 
//DateTimeZone LDateTimeZone = DateTimeZone.forID("Asia/Kolkata"); 
DateTimeZone LDateTimeZone = DateTimeZone.forID("IST"); //deprecated 
System.out.println("Joda-Time zone: " + now.toDateTime(LDateTimeZone)); 

有没有办法处理这两个输入?

+0

始终使用全IANA时区信息数据库的名字 - '亚洲/ Kolkata'。缩写不是唯一的(印度/以色列/爱尔兰?),人性化名称是语言/地区特定的。 –

回答

2

我不能更强烈地反对使用传统java.util.Date。您应该使用相应的java.time类。

java.time.ZonedDateTime中,您可以创建一个时区别名地图并随意填写它。这并不漂亮,但它的工作原理。

Map<String, String> aliasMap = new HashMap<>(); 
aliasMap.put("IST", "Asia/Calcutta"); 
aliasMap.put("Indian Standard Time", "Asia/Calcutta"); 
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("Indian Standard Time", aliasMap)); 
+0

毫无疑问,它是处理这种情况的好方法,但在我的情况下,我需要所有的时区。我很难对所有可用的时区进行硬编码。 –

+0

[Here](http://www.javadb.com/list-possible-timezones-or-zoneids-in-java/)是Java本机支持的所有'ZoneId'的列表。这应该可以帮助您创建所需的别名映射。 –

+0

更好的参考是[here](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones)。 Java中有一些不在该列表中,但这些应该被视为弃用。 –

0

我认为你可以像这样使用乔达

TimeZone timezone; 
timezone = TimeZone.getTimeZone("Indian Standard Time"); 
DateTime dt = new DateTime(new Date()); 
DateTimeZone dtZone = DateTimeZone.forTimeZone(timezone); 
DateTime afterSetTimezone = dt.withZone(dtZone); 
Date date = afterSetTimezone.toLocalDateTime().toDate(); 
System.out.println(date); 
+0

对不起,TimeZone.getTimeZone(“”)函数只支持IST或UTC这样的短名称,因为我已经附上了代码和我的问题。它不适用于TimeZone.getTimeZone(“印度标准时间”)。 –

相关问题