如何在 Java 中从给定的时区名称获取当前时间



我想从给定时区获取当前时间,可以是"IST"或"印度标准时间"等。当输入为"印度标准时间"或"协调世界时"时,我无法获得时间。它仅适用于"IST"或"UTC"或"EST"等。我尝试过Joda-Time和SimpleDateFormat。

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 ) );

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

我不能更强烈地建议不要使用旧版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));

我认为你可以使用 Joda 做到这一点

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);

最新更新