我想从给定的时区获取当前时间,例如“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 ) );
有没有办法处理这两个输入?
我强烈建议不要使用 legacy 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));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句