關於SpringBoot 接受Date類型以及返回時間格式的記錄

最近開始接觸SpringBoot,不得不說他很強大。 
下面說說SpringBoot接受時間的問題,網上的方法很多,我就說說我自己的。

接受時間:

    @NotNull(message = "過期日不能爲空")
    @DateTimeFormat(pattern="yyyy-MM-dd hh:mm:ss")
    private Date expired;


 
用@DateTimeFormat 註解去接受,就是不會去報錯。

返回時間格式方式一:

@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8") 


用接送@JsonFormat 註解去返回,我用的時jackson的json轉換包,SpringBoot 他自身就集成了這些,所以不用去引入。

返回時間格式方式二(這種方式不用註解):

首先去自定義一個類去繼承 StdDateFormat 這個類,然後去重寫他的method.
 

import com.fasterxml.jackson.databind.util.StdDateFormat;
import org.apache.commons.lang3.StringUtils;

import java.text.FieldPosition;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @ClassName CustomDateFormat
 * @Description TODO
 * @Date 2018/8/16 9:32
 * @Author itastro
 * @Version 1.0
 **/
public class CustomDateFormat extends StdDateFormat {


    private static final long serialVersionUID = -3201781773655300201L;

    public static final CustomDateFormat instance = new CustomDateFormat();

    @Override
    /**
     * @ClassName: CustomDateFormat
     * 這個方法可不寫,jckson主要使用的是parse(String)這個方法用來轉換日期格式的,
     * 只要覆蓋parse(String)這個方法即可
     * @date 2018年01月23日 下午4:28:57
     */
    public Date parse(String dateStr, ParsePosition pos) {
        SimpleDateFormat sdf  = null;
        if(StringUtils.isBlank(dateStr)){
            return null;
        }
        if (dateStr.length() == 10) {
            sdf = new SimpleDateFormat("yyyy-MM-dd");
            return sdf.parse(dateStr, pos);
        }
        if (dateStr.length() == 16) {
            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            return sdf.parse(dateStr, pos);
        }
        if (dateStr.length() == 19) {
            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sdf.parse(dateStr, pos);
        }
        if (dateStr.length() == 23) {
            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            return sdf.parse(dateStr, pos);
        }
        return super.parse(dateStr, pos);
    }

    @Override
    public Date parse(String dateStr) {
        ParsePosition pos = new ParsePosition(0);
        SimpleDateFormat sdf  = null;
        if(StringUtils.isBlank(dateStr)){
            return null;
        }
        if (dateStr.length() == 10) {
            sdf = new SimpleDateFormat("yyyy-MM-dd");
            return sdf.parse(dateStr, pos);
        }
        if (dateStr.length() == 16) {
            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            return sdf.parse(dateStr, pos);
        }
        if (dateStr.length() == 19) {
            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sdf.parse(dateStr, pos);
        }
        if (dateStr.length() == 23) {
            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            return sdf.parse(dateStr, pos);
        }
        return super.parse(dateStr, pos);
    }

    public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date, toAppendTo, fieldPosition);
    }

    public CustomDateFormat clone() {
        return new CustomDateFormat();
    }
}


接下來在讓SpringBoot啓動類實現WebMvcConfigurer這個類,重寫他的方法。

@MapperScan("com.bl.station.mapper")
@ComponentScan("com.bl.station.*")
@EnableAutoConfiguration
@ImportResource(locations = {"classpath:mykaptcha.xml"})
@ServletComponentScan
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)// 解決jmx重複註冊bean的問題
@Import(FdfsClientConfig.class)
@EnableSwagger2
public class BlstationWebApplication  extends SpringBootServletInitializer implements WebMvcConfigurer {


    public static void main(String[] args) {
        SpringApplication.run(BlstationWebApplication.class, args);
    }


    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(BlstationWebApplication.class);
    }
   @Bean
    public MappingJackson2HttpMessageConverter getMappingJackson2HttpMessageConverter() {
        MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        //設置日期格式
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setDateFormat(CustomDateFormat.instance);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);
        //設置中文編碼格式
        List<MediaType> list = new ArrayList<MediaType>();
        list.add(MediaType.APPLICATION_JSON_UTF8);
        mappingJackson2HttpMessageConverter.setSupportedMediaTypes(list);
        return mappingJackson2HttpMessageConverter;
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(getMappingJackson2HttpMessageConverter());
    }
}


 
這樣的話他的日期返回格式就正確了。

返回日期是時時間相差8小時的問題 
有時你會發現你的時間和實際時間相差8小時。
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
1
加上 timezone = “GMT+8”,如果還是不行請進行修改數據庫連接配置。

 url: jdbc:mysql://localhost:3306/station?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai


serverTimezone=Asia/Shanghai 設置成他。

還有這個配置我沒試,有興趣的可以試下:

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/station?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai
    username: root
    password: Zn252600@
    jackson:
          date-format: yyyy-MM-dd HH:mm:ss
          time-zone: GMT+8


 
到此結束,親測可用 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章