一、el-date-picker效期起不能大于有效期止
<el-form-item label="有效期起" prop="fvalidbegin"> <el-date-picker v-model="form.fvalidbegin" clearable placeholder="选择有效期起" size="small" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" @change="startChange" > </el-date-picker> </el-form-item> <el-form-item label="有效期止" prop="fvalidend"> <el-date-picker v-model="form.fvalidend" clearable placeholder="选择有效期止" size="small" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" @change="endChange"> </el-date-picker> </el-form-item>
再methods中加入具体的方法:
methods: { startChange(value) { this.$set(this.form, "fvalidbegin", value); if ( new Date(value).getTime() >= new Date(this.form.fvalidend).getTime() ) { this.form.fvalidbegin = ""; this.$message.error("请选择的时间小于有效期止"); } }, endChange(value) { this.$set(this.form, "fvalidend", value); if ( new Date(value).getTime() <= new Date(this.form.fvalidbegin).getTime() ) { this.form.fvalidend = ""; this.$message.error("请选择的时间大于有效期起"); } } }
二、判断字符串是否是yyyyMMddHHmmss格式的日期
/*** * 判断字符串是否是yyyyMMddHHmmss格式 * @param mes 字符串 * @return boolean 是否是日期格式 */ public static boolean isRqSjFormat(String mes){ String format = "([0-9]{4})(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])" + "([01][0-9]|2[0-3])[0-5][0-9][0-5][0-9]"; Pattern pattern = Pattern.compile(format); Matcher matcher = pattern.matcher(mes); if (matcher.matches()) { pattern = Pattern.compile("(\\d{4})(\\d{2})(\\d{2}).*"); matcher = pattern.matcher(mes); if (matcher.matches()) { int y = Integer.valueOf(matcher.group(1)); int m = Integer.valueOf(matcher.group(2)); int d = Integer.valueOf(matcher.group(3)); if (d > 28) { Calendar c = Calendar.getInstance(); c.set(y, m-1, 1); //每个月的最大天数 int lastDay = c.getActualMaximum(Calendar.DAY_OF_MONTH); return (lastDay >= d); } } return true; } return false; }
如果sdf.parse(dateStr)出现异常,说明一定是不符合日期(yyyyMMddHHmmss)格式的字符串,但是不出现异常不一定是符合日期的字符串,比如20191301010101,我们知道,一年中没有第13月,但是SimpleDateFormat会将其解析为2020年第一个月。所以用SimpledateDateFormat判断也不完全可行。以上校验规则可以很好的解决这个问题。摘自(判断字符串是否为日期格式)
三、多种时间格式判断
如果需要其他格式,在parsePatterns数组中追加 public static boolean parseDate(String string) { //多种时间格式判断,可依据实际需求添加时间格式 // String[] parsePatterns = {"yyyy-MM-dd","yyyy年MM月dd日", // "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy/MM/dd", // "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyyMMdd"}; //具体时间格式判断 String[] parsePatterns = {"yyyy-MM-dd HH:mm:ss"}; if (string == null) { return false; } try { DateUtils.parseDate(string, parsePatterns); return true; } catch (ParseException e) { return false; } }