java - Simpledateformat 时区未转换

标签 java datetime simpledateformat

在 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 不包含时区信息,您可以:

  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

关于java - Simpledateformat 时区未转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54276931/

相关文章:

java - 将文件粘贴到文件夹中时获取文件夹的路径

java - JFormattedTextField,接受值[0.1, 100],数字书写不舒服

java SimpleDateFormat.parse 将 UTC 时间转换为亚洲/香港时间

java - ParseException - 无法找出正确的模式

c++ - 将 long int 秒转换为 double 浮点值

java - 使用 SimpleDateFormat 在 Android 中解析长日期

java - 从多个 ArrayList 中删除一个对象

java - 如何在启动时设置一个简单的 Spring 表单

python - 时间增量,以小时、分钟、秒、微秒格式表示

javascript - 解析 utc 时,从现在开始的时刻在 5 小时后返回