大家好,又见面了,我是你们的朋友全栈君。
SimpleDateFormat是线程不安全的 推荐 1.使用ThreadLocal 2.apache commons-lang包的DateFormatUtils
public class Dateformat {
private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
private static ThreadLocal threadLocal = new ThreadLocal();
public static void main(String[] args) throws ParseException {
// apache commons-lang包的DateFormatUtils或者FastDateFormat实现,apache保证是线程安全的,并且更高效
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
String format = dateFormat.format(new Date());
System.out.println("1 常规 ============ "+format);
Date date = getDate(new Date());
System.out.println("2 Calendar ============ "+date);
DateFormat dateFormat1 = getDateFormat();
String format1 = dateFormat1.format(new Date());
System.out.println("3 ThreadLocal ============ "+format1);
String format2 = DateFormatUtils.format(new Date(), DATE_FORMAT);
System.out.println("4 DateFormatUtils============ " + format2);
}
private static Date getDate(Date date) throws ParseException {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.HOUR_OF_DAY, 1);
return (Date) dateFormat.parseObject(dateFormat.format(calendar
.getTime()));
}
public static DateFormat getDateFormat() {
DateFormat df = (DateFormat) threadLocal.get();
if (df == null) {
df = new SimpleDateFormat(DATE_FORMAT);
threadLocal.set(df);
}
return df;
}
}
String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
//sql.timestamp
Timestamp timestamp = new Timestamp(new Date().getTime());
//util.Date
String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/133622.html原文链接:https://javaforall.cn