ssjygl-xsct-service/ssjygl-xsx-common/src/main/java/com/cowr/common/utils/DateTimeUtil.java

68 lines
2.5 KiB
Java
Raw Normal View History

2020-08-07 17:11:12 +08:00
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<SimpleDateFormat> sdf = new ThreadLocal<SimpleDateFormat>() {
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd");
}
};
public static final ThreadLocal<SimpleDateFormat> sdfymd = new ThreadLocal<SimpleDateFormat>() {
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyy年MM月dd日");
}
};
public static final ThreadLocal<SimpleDateFormat> sd = new ThreadLocal<SimpleDateFormat>() {
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM");
}
};
public static final ThreadLocal<SimpleDateFormat> sdfym = new ThreadLocal<SimpleDateFormat>() {
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyy年MM月");
}
};
public static final ThreadLocal<SimpleDateFormat> sdfhms = new ThreadLocal<SimpleDateFormat>() {
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
};
public static final ThreadLocal<SimpleDateFormat> sdfhm = new ThreadLocal<SimpleDateFormat>() {
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;
}
}
}