문제 상황
문제원인
timezone
은 Date, ZonedDateTime 에만 timezone 정보가 있는 사용이 가능한 옵션임문제가 된 코드
@JsonFormat(pattern = "yyyy-MM-dd HH:mm", timezone = "Asia/Seoul")
private final LocalDateTime createdAt;
해결책
구현 목표
@Getter
public class SingleChatResponseDto {
private final Long chatId;
private final SenderResponseDto sender;
private final String content;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm")
private final ZonedDateTime createdAt;
@Builder
public SingleChatResponseDto(Long chatId, SenderResponseDto sender, String content, LocalDateTime createdAt) {
this.chatId = chatId;
this.sender = sender;
this.content = content;
this.createdAt = createdAt.atZone(ZoneId.of("UTC")).withZoneSameInstant(ZoneId.of("Asia/Seoul"));
}
package com.tutorial.tailerbox.config;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.time.format.DateTimeFormatter;
import java.util.TimeZone;
@Configuration
public class DateFormatConfiguration {
private static final String dateFormat = "yyyy-MM-dd";
private static final String datetimeFormat = "yyyy-MM-dd HH:mm:ss";
@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
return jacksonObjectMapperBuilder -> {
jacksonObjectMapperBuilder.timeZone(TimeZone.getTimeZone("Asia/Seoul"));
jacksonObjectMapperBuilder.simpleDateFormat(datetimeFormat);
jacksonObjectMapperBuilder.serializers(new LocalDateSerializer(DateTimeFormatter.ofPattern(dateFormat)));
jacksonObjectMapperBuilder.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(datetimeFormat)));
};
}