GSON
date format
Java
JSON parsing
serialization

GSON - Date format

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Dates are one of the first places where JSON serialization gets messy, because JSON has no native date type. With Gson, you have to decide what string representation your API expects and then configure serialization and deserialization consistently around that decision.

The simplest solution is often GsonBuilder.setDateFormat(...), but that is not always enough. If you need full control over time zones, Java time types, or multiple input formats, custom adapters are often the safer option.

Start With a Clear Date Representation

Suppose you have a model like this:

java
1import java.util.Date;
2
3class Event {
4    private String name;
5    private Date eventDate;
6
7    Event(String name, Date eventDate) {
8        this.name = name;
9        this.eventDate = eventDate;
10    }
11}

Without explicit configuration, Gson can serialize dates in a way that may not match what your API or frontend expects. That is why date handling should be configured deliberately instead of left to defaults.

Use setDateFormat for One Consistent Pattern

If the application uses one stable date format, GsonBuilder.setDateFormat is the simplest configuration:

java
1import com.google.gson.Gson;
2import com.google.gson.GsonBuilder;
3import java.util.Date;
4
5Gson gson = new GsonBuilder()
6    .setDateFormat("yyyy-MM-dd HH:mm:ss")
7    .create();
8
9String json = gson.toJson(new Event("Conference", new Date()));
10System.out.println(json);

This tells Gson how to serialize and deserialize java.util.Date, java.sql.Date, and related legacy date types using the same pattern.

It is a good fit when:

  • your API contract is fixed
  • you control both serialization and deserialization
  • one date format is used consistently everywhere

Use a Custom Adapter When the Rules Are More Complex

If you need exact control, register a custom serializer and deserializer:

java
1import com.google.gson.*;
2import java.lang.reflect.Type;
3import java.text.SimpleDateFormat;
4import java.util.Date;
5import java.util.TimeZone;
6
7class DateAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
8    private final SimpleDateFormat formatter;
9
10    DateAdapter() {
11        formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
12        formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
13    }
14
15    @Override
16    public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
17        return new JsonPrimitive(formatter.format(src));
18    }
19
20    @Override
21    public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
22            throws JsonParseException {
23        try {
24            return formatter.parse(json.getAsString());
25        } catch (Exception ex) {
26            throw new JsonParseException(ex);
27        }
28    }
29}
30
31Gson gson = new GsonBuilder()
32    .registerTypeAdapter(Date.class, new DateAdapter())
33    .create();

This approach is better when time zone handling or exact wire format really matters.

Be Careful With SimpleDateFormat

SimpleDateFormat is not thread-safe, so do not keep one mutable instance around and share it across threads casually. In short examples that is easy to miss, but in real applications you should either:

  • keep the formatter inside a single-threaded adapter instance
  • create it per use
  • or prefer newer Java time APIs where possible

That thread-safety issue is one reason many teams eventually move away from legacy Date handling.

Consider Java Time Types

If your code uses LocalDate, Instant, or OffsetDateTime, Gson does not give them the same seamless support that newer libraries sometimes do. In those cases, custom type adapters are often the cleanest path.

The core idea stays the same: choose one wire format and encode or decode explicitly rather than hoping date objects will serialize the way you want by default.

Common Pitfalls

The most common mistake is letting defaults choose the format and later discovering that another service expects a different string representation.

Another common issue is using setDateFormat when the real problem is more complicated, such as strict UTC normalization or multiple inbound formats. In those cases, a custom adapter is usually clearer.

Developers also forget that SimpleDateFormat is not thread-safe, which can create intermittent bugs in multi-threaded applications.

Finally, be careful about legacy Date versus Java time types. The right Gson configuration for one is not automatically the right configuration for the other.

Summary

  • JSON has no built-in date type, so Gson date formatting must be configured deliberately.
  • Use GsonBuilder.setDateFormat(...) when one consistent legacy date format is enough.
  • Use custom serializers and deserializers when you need precise control over format and time zone.
  • Be aware that SimpleDateFormat is not thread-safe.
  • Choose a clear wire format first, then make Gson match that contract explicitly.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.