Simpledateformat 时区不转换

Simpledateformate timezone not converting

在 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。

我在您的代码中添加了时区输出和明确的 UTC 时区分配给 format1:

    SimpleDateFormat format1 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
    SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    System.out.println(format1.getTimeZone());
    TimeZone utcTimeZone = TimeZone.getTimeZone("UTC");
    format1.setTimeZone(utcTimeZone);
    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

您应该看到 SimpleDateFormat 默认为您当地的时区。明确设置 UTC 应该有效。

如另一个回答所述,您没有为 format1 设置时区。自 java8 以来,您还可以使用 java.time 包来解决此问题。

由于20-01-2019 13:24:56不包含时区信息,您可以:

  1. 将其解析为 LocalDateTime
  2. LocalDateTime 转换为 UTC 中的 ZonedDateTime
  3. 获取时区 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