如何在 JSON 序列化期间将服务器时区添加到 localdatetime?

How to add server timezone to localdatetime during JSON serialization?

我对 RESTful Web 服务中的所有时间戳使用 LocalDateTime,并且所有时间戳初始化和更改都在服务器上进行。
当服务的客户端创建一些资源时,服务器会在内部为该资源分配创建时间戳。

class Resource {
  private String data;
  private LocalDateTime creationTimestamp;

  public Resource(String someData) {
    this.data = someData;
    this.creationTimestamp = LocalDateTime.now();
  }
}

服务器 return 返回 JSON 格式的资源:

{
  "data" : "someData",
  "creationTimestamp" : "2017-09-22T12:03:44.022"
}

当客户端呈现时 creationTimestamp 它不知道创建此时间戳的服务器时区并且呈现时间不正确。

我看到解决它的唯一方法:将应用程序中的所有时间戳更改为 ZonedDateTime,然后 return 将它们与 JSON 中的时区一起返回给客户端。 但是这个方法成本很高。

还有其他方法可以解决这个问题吗?

为什么不将所有时间戳存储为服务器上 java.time.Instant 类型的对象并将即时时间发送到客户端?

这意味着:

class Resource {
  private String data;
  private Instant creationTimestamp;

  public Resource(String someData) {
    this.data = someData;
    this.creationTimestamp = Instant.now();
  }
}

客户端的任务就是在客户端的时区打印时间。

这种方法避免了发送大量数据,也是服务器上的一种小型解决方案。它正在为 在服务器上存储 UTC 时间戳 的概念建模,这可以被所有客户端理解。对于 instants/moments 的客户端格式,例如这样:

DateTimeFormatter dtf = ...; // custom format (maybe localized)
Instant serverInstant = ...;
String formatted = 
    dtf.format(serverInstant.atZone(ZoneId.of("Europe/Berlin"))); 
// or ZoneId.systemDefault()