Skip to content

Instantly share code, notes, and snippets.

@fengt
Last active April 13, 2018 02:42
Show Gist options
  • Save fengt/18aa8f3e706eed76e9263ef99f09e0c4 to your computer and use it in GitHub Desktop.
Save fengt/18aa8f3e706eed76e9263ef99f09e0c4 to your computer and use it in GitHub Desktop.
springBoot接收date类型参数转换

第一种方式(全局)

继承该类WebMvcConfigurerAdapter,注入如下bean:

@Bean
public Converter<String, Date> stringToDateConvert() {
  return new Converter<String, Date>() {
    @Override
    public Date convert(String source) {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
      Date date = null;
      try {
        date = sdf.parse(source);
      } catch (Exception e) {
        e.printStackTrace();
      }
      return date;
    }
  };
}

第二种方式(特定某个controller)

直接在controller中加入如下代码:

@InitBinder
public void initBinder(WebDataBinder binder){
  binder.registerCustomEditor(Date.class, 
      new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
}

第三种方式(继承JsonSerializer)

自定义CustomDateSerializer类,在get属性方法上注入即可:

public class CustomDateSerializer extends JsonSerializer<Date> {    
    @Override
    public void serialize(Date value, JsonGenerator gen, SerializerProvider arg2) throws 
        IOException, JsonProcessingException {      

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = formatter.format(value);

        gen.writeString(formattedDate);

    }
}


//date getter method
@JsonSerialize(using = CustomDateSerializer.class)
public Date getDate() {
    return date;
}

第四种方式(页面js处理)

var __dateConverter = function(param, fmt) {
  if (param) {
    const date = new Date(param);
    if (fmt == 'yyyy-mm') {
      return date.getFullYear() + '-' + (date.getMonth()+1)
    } else if (fmt == 'yyyy-mm-dd hh:mm:ss') {
      return date.getFullYear() + '-' + (date.getMonth()+1)+'-'+date.getDate() 
      + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
    }
    return date.getFullYear() + '-' + (date.getMonth()+1)+'-'+date.getDate();
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment