我有一个日期时间字符串“2018-01-15 01:16:00”,它位于EST时区.我想使用UTC偏移动态地将其转换为另一个时区.我的
javascript代码将此UTC偏移量作为参数传递,并且servlet必须将此日期时间字符串转换/格式化为由提供的偏移量标识的时区.
我尝试了很多方法,包括oracle tutorials中记录的方法,但无法找到解决方案.
以下是我正在尝试的代码,非常感谢任何帮助.
private static final String DATE_FORMAT = “yyyy-MM-dd HH:mm:ss”;
private static final String DEFAULT_TIME_ZONE = ZoneId.SHORT_IDS.get(“EST”);
public static void main(String[] args) throws Exception {
String dateTime = “2018-01-15 02:35:00”;
//parse the datetime using LocalDateTime
LocalDateTime defaultDateTime = LocalDateTime.parse(dateTime, DateTimeFormatter.ofPattern(DATE_FORMAT));
//get the datetime in default timezone
ZoneId defaultZoneId = ZoneId.of(DEFAULT_TIME_ZONE);
ZonedDateTime defaultZoneDateTime = defaultDateTime.atZone(defaultZoneId);
System.out.println(“EST time: “+defaultZoneDateTime.format(DateTimeFormatter.ofPattern(DATE_FORMAT)));
ZonedDateTime utcZonedDateTime = defaultZoneDateTime.withZoneSameInstant(ZoneId.of(“UTC”));
String utcTime = defaultZoneDateTime.withZoneSameInstant(ZoneId.of(“UTC”)).format(DateTimeFormatter.ofPattern(DATE_FORMAT));
System.out.println(“UTC : “+utcTime);
//IST timezone
ZoneOffset offset = ZoneOffset.of(“+05:30”);
OffsetDateTime offsetDate = OffsetDateTime.of(utcZonedDateTime.toLocalDateTime(), offset);
String targetTimeZone = offsetDate.format(DateTimeFormatter.ofPattern(DATE_FORMAT));
System.out.printf(“target time : “+targetTimeZone);
}
OUTPUT
EST time: 2018-01-15 02:35:00
UTC : 2018-01-15 07:37:00
target time : 2018-01-15 07:37:00
预计目标时间:2018-01-15 13:05:00