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

68 lines
2.5 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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;
}
}
}