在 java simpledateformat 中,我无法转换为 IST 的时区。我提供的输入是 UTC,但我想转换为 IST。
SimpleDateFormat format1 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format1.parse("20-01-2019 13:24:56");
TimeZone istTimeZone = TimeZone.getTimeZone("Asia/Kolkata");
format2.setTimeZone(istTimeZone);
String destDate = format2.format(date);
System.out.println(destDate); //2019-01-20 13:24:56
但它必须添加 +5:30 才能使其成为 IST。
最佳答案
正如另一个答案中所述,您没有为 format1
设置时区。从java8开始你也可以使用java.time
包来解决这个问题。
由于 20-01-2019 13:24:56
不包含时区信息,您可以:
- 将其解析为
LocalDateTime
。 - 将
LocalDateTime
转换为 UTC 格式的ZonedDateTime
。 - 获取 IST 时区的同一时刻。
示例:
DateTimeFormatter format1 = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
DateTimeFormatter format2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
ZonedDateTime zonedDateTime = LocalDateTime
.parse("20-01-2019 13:24:56", format1) // parse it without time zone
.atZone(ZoneId.of("UTC")) // set time zone to UTC
.withZoneSameInstant(ZoneId.of("Asia/Kolkata")); // convert UTC time to IST time
System.out.println(format2.format(zonedDateTime)); //2019-01-20 18:54:56
关于java - Simpledateformat 时区未转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54276931/