【问题标题】:how to convert UTC timezone into UK time zone("European/london")如何将 UTC 时区转换为英国时区(“欧洲/伦敦”)
【发布时间】:2021-05-04 14:23:45
【问题描述】:
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
f.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println( f.format(new Date()));

这将是 UTC 时区,我需要在英国(欧洲/伦敦)时区设置。?

【问题讨论】:

标签: java spring-boot


【解决方案1】:

停止使用旧的java.util.Date 类并改用ZonedDateTime

    ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/London"));
    System.out.println(now.format(DateTimeFormatter.ISO_DATE_TIME));

输出:2021-05-04T07:15:22.2556157+01:00[Europe/London]

【讨论】:

    【解决方案2】:
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
    
    OffsetDateTime dateTime = OffsetDateTime.parse("2020-01-01T00:00:00Z");
    OffsetDateTime dateTimeLondon = dateTime.atZoneSameInstant(ZoneId.of("Europe/London")).toOffsetDateTime();
    
    System.out.println(formatter.format(dateTimeLondon));
    

    【讨论】:

      【解决方案3】:

      我猜你需要伦敦时区,它会在 getTimeZOne 方法中将 UTC 替换为你需要的时区。

      SimpleDateFormat f = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");
      f.setTimeZone(TimeZone.getTimeZone("Europe/London"));
      System.out.println(f.format(GregorianCalendar.getInstance().getTime()));
      

      【讨论】:

        【解决方案4】:

        有多种方法可以做到这一点。但在您的问题中,您希望专门针对欧洲/伦敦。 TimeZone 将为您提供执行此操作的便利。

        SimpleDateFormat sdF= new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        sdF.setTimeZone(TimeZone.getTimeZone("Europe/London"));
        System.out.println(sdF.format(new Date()));
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-12-12
          • 2013-05-29
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多