I have stored my timestamps as Timestamp in my MySQL database. I retrieve them on my server, which works with UTC, and then convert these objects to json with Gson. Gson uses the JVM's timezone so it uses UTC on the server, which is what I want.
On my client side, I am in another timezone ("Europe/Amsterdam"), so I try to display dates in that timezone. I am retrieving the json, and then convert it to a list of objects using Gson. The dates that I retrieve at my client are UTC, so that is all going well. The objects have a Date attribute to store the dates. The json looks like this (partly):
{"id":2,"timestamp_start":"Jan 13, 2015 10:44:45 AM GMT",...}
In the conversion I used the following TypeAdapter:
public class DateTypeAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
private final DateFormat dateFormat;
public DateTypeAdapter() {
dateFormat = new SimpleDateFormat("MMM d, yyyy HH:mm:ss a", Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
}
@Override public synchronized JsonElement serialize(Date date, Type type,
JsonSerializationContext jsonSerializationContext) {
return new JsonPrimitive(dateFormat.format(date));
}
@Override public synchronized Date deserialize(JsonElement jsonElement, Type type,
JsonDeserializationContext jsonDeserializationContext) {
try {
return dateFormat.parse(jsonElement.getAsString());
} catch (ParseException e) {
throw new JsonParseException(e);
}
}
}
Then, to show dates in e.g. Tableviews, I simply use this to convert from UTC:
public static String dateToLocalTimeString(Date date) {
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy 'om' HH:mm");
formatter.setTimeZone(TimeZone.getTimeZone("Europe/Amsterdam"));
return formatter.format(date);
}
The problem is: it keeps showing the same date and time as is stored in the database, which is UTC. Even if I get rid of the TypeAdapter, it does.
What am I missing here?
After the conversion, I tested the Date by calling toString(), and it shows the same date and time but now "CEST" appended, which I do not understand. I should be +2, but it is just the same date and time...
UPDATE 2: I now tried the conversion like this (based on Java 8 Date API)
public static String dateToLocalTimeString(Date date) {
LocalDateTime ldt = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy 'om' HH:mm");
String formattedDateTime = ldt.format(formatter);
return formattedDateTime;
}
It stills shows the time 2 hours early. I have printed the epoch timestamp now, and it has just converted GMT -> CEST without converting the time. So I assume the above TypeAdapter is not working, so in my opinion it has something to do with Gson..