I'm running a code that uses Gson Converter with simple date format function and once in a while the date formatting is messes up either it's displaying date back in 1969-1970 depending on time zone or it takes it and displays some random date.
static class DateSerializer implements JsonDeserializer<Date> {
@Override
public Date deserialize(JsonElement jsonElement, Type typeOF, JsonDeserializationContext context)
throws JsonParseException {
for (SimpleDateFormat simpleDateFormat : DATE_FORMATS) {
try {
simpleDateFormat.setLenient(true);
return simpleDateFormat.parse(jsonElement.getAsString());
} catch (ParseException e) {
}
}
return null;
}
}
static {
final TimeZone GMT_TIMEZONE = TimeZone.getTimeZone("GMT");
int i = 0;
for (String format : DATE_FORMAT_STRINGS) {
SimpleDateFormat dateFormat = new SimpleDateFormat(format, Locale.US);
dateFormat.setTimeZone(GMT_TIMEZONE);
DATE_FORMATS[i++] = dateFormat;
}
}
Gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new DateSerializer())
.create();
private static final String[] DATE_FORMAT_STRINGS = new String[]{"yyyy-MM-dd'T'HH:mm:ssZZZZ",
"yyyy-MM-dd'T'HH:mm:ss'Z'"};