如何从 java 中的给定时区名称获取当前时间?
how to get current time from given timezone name in java?
我想从给定的时区获取当前时间,可以是 "IST" 或 "Indian Standard Time" 等。
当输入为 "Indian Standard Time" 或 "Coordinated Universal Time" 时,我无法获得时间。它仅适用于 "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
class。
在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);
我想从给定的时区获取当前时间,可以是 "IST" 或 "Indian Standard Time" 等。 当输入为 "Indian Standard Time" 或 "Coordinated Universal Time" 时,我无法获得时间。它仅适用于 "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
class。
在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);