2021-2-15 前端传入后端日期格式

日期传入错误总结

  • 一:spring.mvc.format.date
  • 二:value="${review.enddate?string('yyyy-MM-dd')}"
  • 三. @JsonFormat

一:spring.mvc.format.date

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/projectCommit?serverTimezone=UTC&useicode=true
    driver-class-name: com.mysql.cj.jdbc.Driver
  mvc:
    format:
      date: dd/MM/yyyy
<input type="date" name="enddate">

解释

将date 类型 格式化

二:value="${review.enddate?string(‘yyyy-MM-dd’)}"

<input type="text" name="enddate" 
value="${review.enddate?string('yyyy-MM-dd')}">

传入后端日期格式错误解决方式
一:

package com.qizhi.config;

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 DateConverterConfig implements Converter<String, Date> {
     


    public Date convert(String source) {
     
        Date date = null;
        try {
     
            date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(source);
        } catch (ParseException e) {
     
// TODO Auto-generated catch block
            e.printStackTrace();
        }
        return date;
    }
}

二:此方法需要在每个控制类(servlet,controller)编写


    @InitBinder
    public void initBinder(ServletRequestDataBinder binder) {
     
       //格式yyyy-MM-dd HH:mm:ss,不能在更改了,灵活性差
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
    }

三:@DateTimeFormat(pattern=“yyyy-MM-dd”)

	@DateTimeFormat(pattern="yyyy-MM-dd")
    private Date startdate;

    @DateTimeFormat(pattern="yyyy-MM-dd")
    private Date enddate;

    private Integer status;

需要传入的字符串类型与这个规则一致

 
    申报结束日期
    
 

三. @JsonFormat

 	@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    @JsonFormat( pattern = "yyyy-MM-dd HH:mm:ss")
    private Date date;
 
    public void setDate(Date date){
     
        this.date = date;
    }
    public Date getDate(){
     
        return date;
    }

@DateTimeFormat(pattern=“yyyy-MM-dd HH:mm:ss”) 表示从前台传入后台的字符串规则 将其 转为日期

@JsonFormat(pattern = “yyyy-MM-dd HH:mm:ss” )表示接口返回的string日期 按照 这个规则 格式化字符串

一般这个两个都是同时使用,保证传入@JsonFormat的字符串格式@DateTimeFormat一致

你可能感兴趣的:(字符串,spring,java)