Answer the question
In order to leave comments, you need to log in
How to remove the timezone change for the current one when parsing with the gson library?
How to remove the timezone change for the current one when parsing with the gson library?
For example, from the string I’m raising the date:
2020-05-26T17:34:00+0200
I translate it into a date object, after which I translate it back into a string and get 2020-05-26T18:34:00+0300
In the date object itself, the date is already with my current belt. How to leave the date as is when parsing
Answer the question
In order to leave comments, you need to log in
You need to register your date converter.
public class GsonUTCDateAdapter implements JsonSerializer<Date>,JsonDeserializer<Date> {
private final DateFormat dateFormat;
public GsonUTCDateAdapter() {
dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
}
@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);
}
}
}
Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new GsonUTCDateAdapter()).create();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question