SpringMVC 关于日期(Date)的接收与返回

博客介绍了Spring中日期格式的配置方法,包括局部配置和全局配置。局部配置有JSON方式(Jackson和FastJson)以及表单方式;全局配置采用Spring Boot配置方式(仅适用于Jackson),还涉及接收多种、单种日期格式以及返回指定日期格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

局部配置

JSON方式 (Jackson)

import com.fasterxml.jackson.annotation.JsonFormat;

@Data
public class MyVO {
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone="GMT+8")
    private Date date;
}

JSON方式 (FastJson)

import com.alibaba.fastjson.annotation.JSONField;

@Data
public class MyVO {
    @JSONField(format = "yyyy-MM-dd HH:mm:ss")
    private Date date;
}

表单方式(只适用于接收)

import org.springframework.format.annotation.DateTimeFormat;

@Data
public class MyVO {
    @DateTimeFormat( pattern = "yyyy-MM-dd HH:mm:ss")
    private Date date;
}

全局配置

Spring Boot配置方式(只适用于Jackson)

application.yml

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

接收多种日期格式

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

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

@Component
public class DateConverter implements Converter<String, Date> {
    //添加不同的日期格式
    private static final String[][] datePatternArray = new String[][]{
            {"yyyy-MM-dd", "^\\d{4}-\\d{1,2}-\\d{1,2}$"},
            {"yyyy-MM-dd HH:mm", "^\\d{4}-\\d{1,2}-\\d{1,2}\\s\\d{1,2}:\\d{1,2}$"},
            {"yyyy-MM-dd HH:mm:ss", "^\\d{4}-\\d{1,2}-\\d{1,2}\\s\\d{1,2}:\\d{1,2}:\\d{1,2}$"}
    };

    @Override
    public Date convert(String source) {
        try {
            for (int i = 0; i < datePatternArray.length; i++) {
                if (source.matches(datePatternArray[i][1])) {
                    SimpleDateFormat dateFormat = new SimpleDateFormat(datePatternArray[i][0]);
                    dateFormat.setLenient(false);//指定日期/时间解析为不严格
                    return dateFormat.parse(source);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

接收单种日期格式

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RestControllerAdvice;

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

@RestControllerAdvice
public class Advice {
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));   //true:允许输入空值,false:不能为空值
    }
}

返回指定日期格式

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.text.SimpleDateFormat;
import java.util.List;

@Configuration
public class MessageJSON implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        for (HttpMessageConverter converter : converters) {
            if (converter instanceof  FastJsonHttpMessageConverter) {
                FastJsonHttpMessageConverter fastConverter = (FastJsonHttpMessageConverter)converter;
                fastConverter.getFastJsonConfig().setDateFormat("yyyy-MM.dd HH.mm.ss");
            } else if (converter instanceof MappingJackson2HttpMessageConverter) {
                MappingJackson2HttpMessageConverter jacksonConverter = (MappingJackson2HttpMessageConverter)converter;
                jacksonConverter.getObjectMapper().setDateFormat( new SimpleDateFormat("yyyy-MM.dd HH.mm.ss"));
            }
        }
    }
}

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值