Skip to content

Instantly share code, notes, and snippets.

@StefRe
Created January 16, 2020 12:25
Show Gist options
  • Save StefRe/89c33a7695453a0fedbd1e91096510eb to your computer and use it in GitHub Desktop.
Save StefRe/89c33a7695453a0fedbd1e91096510eb to your computer and use it in GitHub Desktop.
Custom joda date format with Jackson serialization
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import com.fasterxml.jackson.datatype.joda.cfg.JacksonJodaDateFormat;
import com.fasterxml.jackson.datatype.joda.ser.LocalDateSerializer;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.LocalDate;
public class CustomJodaFormat {
public static void main(final String[] args) throws JsonProcessingException {
SimpleModule customJodaModule = new SimpleModule();
customJodaModule.addSerializer(LocalDate.class,
new LocalDateSerializer(new JacksonJodaDateFormat(DateTimeFormat.forPattern("dd.MM.yyyy")), 1));
ObjectMapper om = new ObjectMapper();
om.registerModule(new JodaModule());
om.registerModule(customJodaModule);
System.out.println(om.writerWithDefaultPrettyPrinter().writeValueAsString(new LocalDate(2020, 1, 16)));
}
}
@StefRe
Copy link
Author

StefRe commented Jan 16, 2020

This gives "16.01.2020" as opposed to the standard format "2020-01-16" from simply

        ObjectMapper om = new ObjectMapper();
        om.registerModule(new JodaModule());
        om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment