neptuno
V2EX  ›  问与答

求助,关于 Java 时区的问题

  •  
  •   neptuno · Jun 2, 2022 · 2170 views
    This topic created in 1441 days ago, the information mentioned may be changed or developed.
    框架是 Spingboot ,json 是 fastjson ,部分缓存用的是 gson 。数据库+服务器时区都是北京时间,怎么设置才能使接口返回的是泰国时间?
    Supplement 1  ·  Jun 6, 2022
    最后采取了 @JSONField(name="receive_time",serializeUsing = DateSerializer.class)的方式,DateSerializer 中判断 LocaleContextHolder.getLocale()来区分不同的语言。如果用户选择了泰语,则使用泰国时区。否则返回中国时间。
    10 replies    2022-06-06 14:29:35 +08:00
    DreamStar
        1
    DreamStar  
       Jun 2, 2022
    序列化方面不多赘述, jdk8 时间类库足以

    ```java
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    Instant now = Instant.now();
    System.out.printf(
    "中国: %s%n 泰国: %s",
    formatter.format(now.atZone(ZoneId.of("Asia/Shanghai"))),
    formatter.format(now.atZone(ZoneId.of("Asia/Bangkok")))
    );
    ```
    neptuno
        2
    neptuno  
    OP
       Jun 2, 2022
    @DreamStar 这种方式是不是只能每个字段单独处理,我现在很多接口都返回了 date ,有方式可以批量设置吗
    lower
        3
    lower  
       Jun 2, 2022
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss" , timezone = "GMT+7") 直接字段上加注解???
    IsNotGood
        4
    IsNotGood  
       Jun 2, 2022 via iPhone
    在 yml 里面配置 date-format-pattern ?没遇到这种混合的情况
    dcsuibian
        5
    dcsuibian  
       Jun 2, 2022 via Android
    我都是传个时间戳让前端自己调
    neptuno
        6
    neptuno  
    OP
       Jun 2, 2022
    @lower 有很多接口都有 date 类型返回,不知道有没有办法,全局设置 fastjson 的 timezone ,网上查到的都是 jackson 的配置。我看 fastjson 默认是使用 Timezone.getdefault(),但没找到手动设置的地方
    night98
        7
    night98  
       Jun 3, 2022
    偷懒的话写个 date 类型的自定义序列化器注入进去,里面直接设置为泰国时区格式化
    neptuno
        8
    neptuno  
    OP
       Jun 3, 2022 via iPhone
    @night98 #7 谢谢回复,我下周试一下
    neptuno
        9
    neptuno  
    OP
       Jun 6, 2022
    @lower 这个我试了一下,是 jackson 的注解,我现在项目里用的是 fastjson ,会忽略这个注解
    neptuno
        10
    neptuno  
    OP
       Jun 6, 2022
    @DreamStar
    @IsNotGood
    @dcsuibian
    @night98 最后解决方案出来了哈,各位有需要的可以看一下
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1796 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 51ms · UTC 16:20 · PVG 00:20 · LAX 09:20 · JFK 12:20
    ♥ Do have faith in what you're doing.