Skip to content

7.后端将日期字符串转化为Date

JustCoding-Hai edited this page Nov 8, 2020 · 1 revision

前端使用el-date-picker选择时间

    <el-date-picker
          v-model="dateScope"
          type="datetimerange"
          range-separator=""
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :editable="false"
          :unlink-panels="true"
          value-format="yyyy-MM-dd HH:mm:ss"
          class="topControlsBar">
  </el-date-picker>

dateScope发送到后端是用String字符串数组,后端控制器接受

    @GetMapping("/page")
    public RespPageBean getAllGroupMsgContentByPage(@RequestParam(value = "page",defaultValue = "1") Integer page,
                                                    @RequestParam(value = "size",defaultValue = "10") Integer size,
                                                    String nickname, Integer type,
                                                    Date[] dateScope){
        return groupMsgContentService.getAllGroupMsgContentByPage(page,size,nickname,type,dateScope);
    }

定义一个全局类型转换器来解决类型转换问题

@Component
public class DateConverter implements Converter<String, Date> {

  SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  @Override
  public Date convert(String s) {
    Date date = null;
    if (s!=null&&!"".equals(s)){
      try {
       date= simpleDateFormat.parse(s);
      } catch (ParseException e) {
        e.printStackTrace();
      }
    }
    return date;
  }
}
Clone this wiki locally