Date Formatting Techniques in Spring Boot Applications
This article explains various Spring Boot approaches for formatting dates in API responses, covering frontend JavaScript utilities, Java SimpleDateFormat and DateTimeFormatter, global Jackson settings, annotation‑based formatting, custom converters, ControllerAdvice initBinder, and timestamp output methods.
Common Application Scenarios
Unified date formats improve readability and maintainability when different systems exchange data, especially in front‑end/back‑end separation, database storage, and log recording.
Common Date Formatting Methods
Frontend Time Formatting
When the back‑end delegates formatting to the front‑end, a JavaScript utility function can be used:
function dateFormat(fmt, date) {
let ret;
const opt = {
"Y+": date.getFullYear().toString(),
"m+": (date.getMonth() + 1).toString(),
"d+": date.getDate().toString(),
"H+": date.getHours().toString(),
"M+": date.getMinutes().toString(),
"S+": date.getSeconds().toString()
};
for (let k in opt) {
ret = new RegExp("(" + k + ")").exec(fmt);
if (ret) {
fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")));
}
}
return fmt;
}
let date = new Date();
dateFormat("YYYY-mm-dd HH:MM:SS", date); // >>>2021-07-25 21:45:12SimpleDateFormat Formatting
For JDK 8 and earlier, SimpleDateFormat formats Date objects:
// Define formatter
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Format a Date instance
String date = dateFormat.format(new Date());In a Spring controller, the formatter can be applied to each entity field:
@RequestMapping("/list")
public List
getList() {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
List
list = userMapper.getList();
list.forEach(item -> {
item.setCtime(dateFormat.format(item.getCreatetime()));
item.setUtime(dateFormat.format(item.getUpdatetime()));
});
return list;
}DateTimeFormatter Formatting
Since JDK 8, DateTimeFormatter replaces SimpleDateFormat and is thread‑safe:
@RequestMapping("/list")
public List
getList() {
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
List
list = userMapper.getList();
list.forEach(item -> {
item.setCtime(dateFormat.format(item.getCreatetime()));
item.setUtime(dateFormat.format(item.getUpdatetime()));
});
return list;
}Global Time Formatting via Configuration
Adding two lines to application.properties (or application.yml ) makes Jackson format all date fields globally:
# Global date format
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
# Time zone
spring.jackson.time-zone=GMT+8Jackson automatically applies this format when serializing response objects.
Partial Formatting with @JsonFormat
Annotate specific fields in an entity to control their format:
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.util.Date;
@Data
public class UserInfo {
private int id;
private String username;
@JsonFormat(pattern = "yyyy-MM-dd hh:mm:ss", timezone = "GMT+8")
private Date createtime;
private Date updatetime;
}Custom Parameter Converters
Implement Converter<String, LocalDate> or Converter<String, LocalDateTime> to parse incoming strings:
@Configuration
public class DateConverterConfig {
@Bean
public Converter
localDateConverter() {
return source -> LocalDate.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
}
@Bean
public Converter
localDateTimeConverter() {
return source -> LocalDateTime.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
}Using @DateTimeFormat Annotation
Apply @DateTimeFormat on a field to convert a string to a date type:
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date birthday;ControllerAdvice with initBinder
Define a global binder to convert string parameters to LocalDateTime :
@ControllerAdvice
public class InitBinderDateController {
@InitBinder("date")
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(LocalDateTime.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) {
if (!StringUtils.isEmpty(text)) {
setValue(LocalDateTime.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
}
}
});
}
}Backend Global Settings via Beans
Configure Jackson serializers/deserializers for LocalDateTime in a @Configuration class:
@Configuration
public class LocalDateTimeSerializerConfig {
private static final String PATTERN = "yyyy-MM-dd HH:mm:ss";
@Bean
public LocalDateTimeSerializer localDateTimeSerializer() {
return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(PATTERN));
}
@Bean
public LocalDateTimeDeserializer localDateTimeDeserializer() {
return new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(PATTERN));
}
@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
return builder -> {
builder.serializerByType(LocalDateTime.class, localDateTimeSerializer());
builder.deserializerByType(LocalDateTime.class, localDateTimeDeserializer());
};
}
}Returning Timestamps
Configure Spring Boot to output dates as Unix timestamps and expose them via a simple REST endpoint:
# application.properties
spring.mvc.format.date=unix public class MyEntity {
private Date date;
// getters and setters
}
@RestController
public class MyController {
@GetMapping("/entity")
public MyEntity getEntity() {
MyEntity entity = new MyEntity();
entity.setDate(new Date());
return entity;
}
}The response will contain the date as a numeric timestamp, e.g., {"date":1678912345678} .
Top Architecture Tech Stack
Sharing Java and Python tech insights, with occasional practical development tool tips.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.