SpringBoot時間類型轉換

開發中前端常常傳的日期類型是String的,而後端在存入數據庫中的時候,是Date類型的,這時候我們通常都是手動轉一下,或者在Converter中轉一下,這樣是比較麻煩的。 下面介紹一下boot開發spring類型轉換
1.自定義DateConverter

import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 時間類型轉換類
 */
public class DateConverter implements Converter<String, Date> {

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public Date convert(String s) {
        if(StringUtils.isEmpty(s)) {
            return null;
        }
        try {
            return simpleDateFormat.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;

    }
}

2.註冊引用類型轉換類
2.1 自定義一個類 實現WebMvcConfigurer接口並 使用@Configuration註解
2.2 實現WebMvcConfigurer接口中的addInterceptors方法
2.3 註冊引用時間類型轉換類

import com.example.springboot_day04_01.utils.DateConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
		//實現WebMvcConfigurer接口中的addInterceptors方法
    public void addFormatters(FormatterRegistry registry) {
    	//註冊引用時間類型轉換類
        registry.addConverter(new DateConverter());
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章