1. Overview

In this article, we will learn Spring Gson custom date format or we can say how to convert Date to Long, Date to custom format, Date to specific timezone in Gson with spring or spring boot application. Word is running with multiple timezone and it’s obvious that we need to provide default timezone while working with Json conversion using Gson.

By default spring will use Jackson for convert Java Object to Json, If you are not aware about how to configure Gson in spring or spring boot application then here is details and example for the same.

If you looking for customize date format with Jackson then here is article to customize date format in Jackson with examples.

2. Custom format using application.properties or yml

Spring boot have property called spring.gson.date-format using that we can set date and time format. It is supporting Java Standard format.

application.properties

spring.gson.date-format=MM-dd-YYYY

or

application.yml

spring:
  gson:
    date-format: MM-dd-yyyy

3. Custom date format using GsonBuilder

If you are not using spring boot and using normal spring application then you may create bean of GsonBuilder and support date-time format over there. It is supporting Java Standard format.

@Bean
GsonBuilder gsonBuilder(){
    GsonBuilder gsonBuilder=new GsonBuilder();
    gsonBuilder.setDateFormat("MM-dd-yyyy");
    return gsonBuilder;
}

4. Gson Date to long

Gson does not provide any direct configuration for conversation of Date to Long, But we can custom any data type while serializing and de-serializing the objects.

Here we have implemented JsonSerializer and JsonDeserializer interface and register with adapter. serialize() and deserialize() are the methods that we have overridden where we have written our custom code for convert Date to Long at time of serialization and Long to Date at time of de-serialization.

    @Bean
    GsonBuilder gsonBuilder(){
        GsonBuilder gsonBuilder=new GsonBuilder();
        gsonBuilder.registerTypeAdapter(Date.class, new JsonSerializer<Date>() {
            
            @Override
            public JsonElement serialize(Date date, Type typeOfSrc, JsonSerializationContext context) {
                // convert date to long
                return new JsonPrimitive(date.getTime());
            }
        });

        gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer() {
            @Override
            public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws
                                                                                                          JsonParseException {
                // convert long to date
                return new Date(json.getAsLong());
            }
        });
        return gsonBuilder;
    }

5. Gson Date with Time Zone

As same like Long conversation, Gson does not provide support like timezone conversation, Generally our application are running in UTC timezone, but when we send Json response then we need different timezone so we need to convert it to another timezone.

NOTE: Its not always requires that we need to send after converting to timezone , but it based on our implementation and application requirements.

@Bean
    GsonBuilder gsonBuilder(){
        GsonBuilder gsonBuilder=new GsonBuilder();

        final DateFormat dateFormat;
        dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");      
        dateFormat.setTimeZone(TimeZone.getTimeZone("America/New_York"));   //This is the format I need

        gsonBuilder.registerTypeAdapter(Date.class, new JsonSerializer<Date>() {

            @Override
            public JsonElement serialize(Date date, Type typeOfSrc, JsonSerializationContext context) {
                // convert date to long
                return new JsonPrimitive(dateFormat.format(date));
            }
        });

        gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer() {
            @Override
            public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws
                                                                                                   JsonParseException {
                try {
                    return dateFormat.parse(json.getAsString());
                }catch (Exception e){
                    return null;
                }
            }
        });
        return gsonBuilder;
    }

4. Conclusion

In this article, We learned about custom date format with Gson and how we can override custom date type while serializing and de-serializing Java Objects. As compare to Jackson, Gson provides less configurable options as per my opinion otherwise both have there own advantages and disadvantages.

5. References

6. Source Code

Git : spring-Gson-custom-date-format

Was this post helpful?
Let us know, if you liked the post. Only in this way, we can improve us.
Yes
No

Leave a Reply

Your email address will not be published. Required fields are marked *