spring boot 統一處理時間參數


在網上面搜了很多都發現有點沒有描述清楚應該分兩種情況

1.對於非請求體json參數(url參數,表單參數)

  我選擇的是添加一個時間轉換器

      

package com.htsc.thfx.framework.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @ClassName: InterceptorConfig
 * @Description: TODO
 * @author: K0180041
 * @date: 2018年7月25日 下午6:51:48
 */
@Configuration
public class WebMvcConfigurerConfig extends WebMvcConfigurerAdapter {

 

    @Override
    public void addFormatters(FormatterRegistry registry) {
        // lambda 會報錯
        registry.addConverter(new Converter<String, Date>() {
            @Override
            public Date convert(String stringDate) {
                SimpleDateFormat simpleDateFormat;
                if (stringDate.contains(" ")) {
                    simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                } else {
                    simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                }
                try {
                    return simpleDateFormat.parse(stringDate);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                return null;
            }


        });
    }
}

 

2.對於請求體json參數

在時間類型添加暫時沒有找到合適的全局處理的方式,思路應該是修改json的序列化的方式......

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM