3

I use LocalDateTime for all timestamps in the RESTful web service and all timestamps initialization and changes are made on the server.
When the client of the service creates some resource then the server internally assigns creation timestamp to this resource.

class Resource {
  private String data;
  private LocalDateTime creationTimestamp;

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

The server returns a resource back in JSON format:

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

When the client renders creationTimestamp it doesn't know the server timezone in which this timestamp was created and renders time incorrectly.

I see the only way to solve it: change all timestamps in the application to ZonedDateTime and return them back to the client together with timezone in JSON. But this approach is very expensive.

Is there any other way to solve this problem?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Ilya Zinkovich
  • 4,082
  • 4
  • 25
  • 43
  • 1
    A `LocalDateTime` doesn't have a timezone. Also, which JSON serialization library are you using? – Mark Rotteveel Sep 22 '17 at 09:26
  • @MarkRotteveel, I know that it doesn't have a timezone, therefore I'm thinking about migrating to ZonedDateTime. I use Jackson for JSON serialization – Ilya Zinkovich Sep 22 '17 at 12:53

1 Answers1

2

Why not storing all timestamps as objects of type java.time.Instanton the server and sending instants to the clients?

This means:

class Resource {
  private String data;
  private Instant creationTimestamp;

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

It is then the task of the client to print the instant in the timezone of the client.

That approach avoids sending large amounts of data and is also a slim solution on the server. And it is modelling the concept to store UTC-timestamps on the server which can be understood by all clients. For client-side formatting of instants/moments, for example this way:

DateTimeFormatter dtf = ...; // custom format (maybe localized)
Instant serverInstant = ...;
String formatted = 
    dtf.format(serverInstant.atZone(ZoneId.of("Europe/Berlin"))); 
// or ZoneId.systemDefault() 
Meno Hochschild
  • 42,708
  • 7
  • 104
  • 126