使用FastDateFormat来代替JDK自带的DateFormat

之前一直使用SimpleDateFormat来做Date到String的类型转换,现建议使用apache commons-lang3中的FastDateFormat。

因为JDK里自带的SimpleDateFormat存在线程安全问题,而且FastDateFormat的效率要高于SimpleDateFormat。

maven依赖:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.5</version>
</dependency>

代码:

public class Test {
    public static void main(String[] args) {
        Date date = new Date();
        FastDateFormat fdf = FastDateFormat.getInstance("yyyy-MM-dd");
        System.out.println(fdf.format(date));
    }
}

 其实,commons-lang3包中针对FastDateFormat这个类封装了一个工具类给我们使用!DateFormatUtils~

public class Test {
    public static void main(String[] args) {
        String format = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
        System.out.println(format);
    }
}
原文地址:https://www.cnblogs.com/winner-0715/p/7185744.html