springboot 日期時間格式化常見處理方式

目標

  • 一、請求入參string(指定格式)轉date,支持get、post(content-type=application/json)
  • 二、返回數據date轉爲指定日期時間格式的strin
  • 三、支持java8日期api,如:LocalTime、LocalDate和LocalDateTime

JSON入參及返回值全局處理

請求類型爲:post,content-type=application/json, 後臺用@RequestBody接收,默認接收及返回值格式爲:yyyy-MM-dd HH:mm:ss前端

方式一 在application.propertities文件中增長以下內容:java

spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
複製代碼

點評:spring

  • 1 支持(content-type=application/json)請求中格式爲yyyy-MM-dd HH:mm:ss的字符串,後臺用@RequestBody接收,及返回值date轉爲yyyy-MM-dd HH:mm:ss格式string;
  • 二、不支持(content-type=application/json)請求中yyyy-MM-dd等類型的字符串轉爲date;
  • 三、不支持java8日期api。

方式二json

自定義MappingJackson2HttpMessageConverter中objectMapper指定日期類型序列化即反序列化:api

@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    ObjectMapper objectMapper = new ObjectMapper();

    // 忽略json字符串中不識別的屬性
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    // 忽略沒法轉換的對象 
    objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    // PrettyPrinter 格式化輸出
    objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    // NULL不參與序列化
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    // 指定時區
    objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
    // 日期類型字符串處理
    objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    
    // java8日期日期處理
    JavaTimeModule javaTimeModule = new JavaTimeModule();
    javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
    javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
    javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
    javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
    javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
    javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
    objectMapper.registerModule(javaTimeModule);

    converter.setObjectMapper(objectMapper);
    return converter;
}
複製代碼

點評:springboot

  • 一、支持(content-type=application/json)請求中格式爲yyyy-MM-dd HH:mm:ss的字符串,後臺用@RequestBody接收,及返回值date轉爲yyyy-MM-dd HH:mm:ss格式string;
  • 二、支持java8日期api。
  • 三、不支持(content-type=application/json)請求中yyyy-MM-dd等類型的字符串轉爲date;

以上兩種方式爲json入參的全局化處理,推薦使用方式二,尤爲適合大型項目在基礎包中全局設置。bash

JSON入參及返回值局部差別化處理

場景: 假如全局日期時間處理格式爲:yyyy-MM-dd HH:mm:ss,可是某個字段要求接收或返回日期(yyyy-MM-dd)。app

方式一ide

使用springboot自帶的註解@JsonFormat(pattern = "yyyy-MM-dd"),以下所示:post

@JsonFormat(pattern = "yyyy-MM-dd", timezone="GMT+8")
private Date releaseDate;
複製代碼

點評: springboot默認提供,功能強大,知足常見場景使用,並可指定時區。

方式二

自定義日期序列化與反序列化,以下所示:

/**
 * 日期序列化
 */
public class DateJsonSerializer extends JsonSerializer<Date> {
    @Override
    public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws
            IOException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        jsonGenerator.writeString(dateFormat.format(date));
    }
}

/**
 * 日期反序列化
 */
public class DateJsonDeserializer extends JsonDeserializer<Date> {

    @Override
    public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            return dateFormat.parse(jsonParser.getText());
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
}

/**
 * 使用方式
 */
@JsonSerialize(using = DateJsonSerializer.class)
@JsonDeserialize(using = DateJsonDeserializer.class)
private Date releaseDate;


複製代碼

get請求及post表單日期時間字符串格式轉換

方式一

實現org.springframework.core.convert.converter.Converter,自定義參數轉換器,以下:

@Component
public class DateConverter implements Converter<String, Date> {

    private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";

    @Override
    public Date convert(String value) {
        /**
         * 可對value進行正則匹配,支持日期、時間等多種類型轉換
         * @param value
         * @return
         */
        SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
        try {
            return formatter.parse(value);
        } catch (Exception e) {
            throw new RuntimeException(String.format("parser %s to Date fail", value));
        }
    }
}
複製代碼

點評: 建議使用方式一時,對前端傳遞的string進行正則匹配,如yyyy-MM-dd HH:mm:ss、yyyy-MM-dd、 HH:mm:ss等,進行匹配。以適應多種場景。

方式二

使用spring自帶註解@DateTimeFormat(pattern = "yyyy-MM-dd"),以下:

@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date startDate;
複製代碼

點評: 若是使用了方式一,spring會優先使用方式一進行處理,即方式二不生效。

相關文章
相關標籤/搜索