Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gson Converter with SimpleDateFormat

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'"};
like image 622
Andrei Chernyshev Avatar asked Dec 29 '25 22:12

Andrei Chernyshev


1 Answers

The problem is that SimpleDateFormat is not thread-safe. Your deserialization is happening across multiple threads to improve performance, but due to the non-thread-safety of SimpleDateFormat, you occasionally will get garbage back in your parsed dates.

Two options for solving this problem are creating a new SimpleDateFormat each time you need it, or enforcing atomicity by doing something such as creating a lock on your date format.

For example, GSON's DefaultDateTypeAdapter takes the latter approach.

like image 171
Bryan Herbst Avatar answered Jan 01 '26 14:01

Bryan Herbst