两者最大的区别是,Java8的DateTimeFormatter是线程安全的,而SimpleDateFormat并不是线程安全。
所以可以用两种方式来替换SimpleDateFormat:
方式一:采用DateUtils工具类的方式
说明:这样就限制了SimpleDateFormat只能在当前线程内共享,这样就避免了多线程导致的线程安全问题。
private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>() {
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd");
}
};
//日期转字符串
public static String format(Date date) {
return threadLocal.get().format(date);
}
//字符串转日期
public static String parse(String str){
return threadLocal.get.parse(str);
}
方式二:采用JDK8的新特性DateTimeFormatter
说明:DateTimeFormatter是线程安全的,在java.time中
public static void main(String[] args) {
//DateTimeFormatter 线程安全的日期格式化类
//日期转换为字符串 ---通过模式字符串来创建DateTimeFormatter格式器,一般用这个
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy年MM月dd日 hh:mm:ss");
LocalDateTime now = LocalDateTime.now();
String format1 = now.format(format);
System.out.println(format1);
//直接使用常量创建DateTimeFormatter格式器 ISO_DATE 2018-11-12 / ISO_LOCAL_TIME 14:03:24.266 / ISO_LOCAL_DATE_TIME 2018-11-12T14:03:54.363 / BASIC_ISO_DATE 20181112 等等
DateTimeFormatter isoDate = DateTimeFormatter.BASIC_ISO_DATE;
LocalDateTime now2 = LocalDateTime.now();
String format2 = now.format(isoDate);
System.out.println(format2);
//字符串转换为日期
LocalDateTime now3 = LocalDateTime.now();
DateTimeFormatter format3 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); //HH24小时制,hh12小时制
String str = "2014-04-12 01:06:09";
// LocalDate 不包含时分秒,只有年月日
LocalDate parse = LocalDate.parse(str, format3);
System.out.println(parse+" parse");
//LocalDateTime 年月日时分秒都有,不过要注意,使用localdatetime的时候,格式的时间只能是24小时制,不能用hh,不然会报错
LocalDateTime parse1 = LocalDateTime.parse(str, format3);
System.out.println(parse1+" parse1");
//如果一个字符串没有时分秒,那么是不能直接转换成LocalDateTime的
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate ld = LocalDate.parse("20180306", dtf);
//需要指定时分秒,localTime 指定时分秒部分和localDate可以组合使用
LocalDateTime ldt = LocalDateTime.of(ld, LocalTime.of(12,12,12));
System.out.println(ldt+" ldt");
//instant格式化为字符串
I Instant now = Instant.now();
String format = DateTimeFormatter.ofPattern("yyyy:MM:dd HH:mm:ss").format(now);
}