1. 程式人生 > >SpringBoot處理前端頁面傳入的時間字串

SpringBoot處理前端頁面傳入的時間字串

在使用SpringBoot日常開發中,發現前端頁面傳入的時間字串無法自動轉換成日期格式,後臺在處理會比較麻煩。

多方查閱,找到此處理方式:

1.在啟動類Application中,新增方法處理:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.
SpringBootServletInitializer; import org.springframework.context.annotation.Bean; import org.springframework.core.convert.converter.Converter; import java.text.SimpleDateFormat; import java.util.Date;
@Bean
public Converter<String, Date> addNewConvert() {
return new Converter<String, Date>() {
@Override public Date convert(String source) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date = null; try { date = sdf.parse( source); } catch (Exception e) { e.printStackTrace(); } return date; } }; }

2.然後在配置檔案application.properties檔案中新增

spring.jackson.date-format
=yyyy-MM-dd

1、針對json格式:在配置檔案中加以下配置

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

2、針對form表單格式,加下面這句配置就可以

 spring.mvc.dateFormat = yyyy-MM-dd HH:mm:ss

3、也可以在pojo中對特定的date型別屬性加了以下配置

    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss")