package com.cowr.common.utils; import com.jfinal.kit.StrKit; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class DateTimeUtil { public static final String ymdhms = "yyyy-MM-dd HH:mm:ss"; public static final ThreadLocal sdf = new ThreadLocal() { protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd"); } }; public static final ThreadLocal sdfymd = new ThreadLocal() { protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy年MM月dd日"); } }; public static final ThreadLocal sd = new ThreadLocal() { protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy-MM"); } }; public static final ThreadLocal sdfym = new ThreadLocal() { protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy年MM月"); } }; public static final ThreadLocal sdfhms = new ThreadLocal() { protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); } }; public static final ThreadLocal sdfhm = new ThreadLocal() { protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd HH:mm"); } }; /** * 验证是否符合格式的时间字符串 * @param str * @param fmt * @return */ public static boolean isValidDate(String str, String fmt) { if (!StrKit.notBlank(str, fmt)) { return false; } SimpleDateFormat sdf = new SimpleDateFormat(fmt); try { // 设置lenient为false. // 否则SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01 sdf.setLenient(false); Date tm = sdf.parse(str); return sdf.format(tm).equals(str); // 将转换后的时间再格式化,和原字符串对比,检查是否一致 } catch (ParseException e) { // e.printStackTrace(); // 如果throw java.text.ParseException或者NullPointerException,就说明格式不对 return false; } } }