Java8新特性-日期相關類操作


JDK8以前使用SImpleDateFormate類格式化日期,因為在SImple DateFormate中存在Calendar實例引用,而在caleander中得establish中存在clear()和set()操作,在多線程情況下會產生問題,導致后面得后面線程修改之前線程,因此SImpleDateFormate是線程不安全得;

JDK8中使用DateTimeFormate日期格式化。在JDK8中新增得類是final關鍵子修飾不可變線程安全,所以可以安全的操作日期轉換。

解決SImpleDateFormate線程不安全:

    采用局部變量的方式,缺點是每次調用方法時,會有對象產生,對象的回收

    采用synchronized或lock,缺點是同一時間內只有一個線程在操作,降低效率

    采用第三方框架:joda-time

    使用ThreadLocal采用線程副本的方式,使每個線程自身擁有SimpleDateFormate對象。

public class DateUtil {

    private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
    private static ThreadLocal threadLocal = new ThreadLocal();

    public static Date parse(String textDate) throws ParseException {
        return getDateFormat().parse(textDate);
    }
    public static String format(Date date) throws ParseException {
        return getDateFormat().format(date);
    }
    public static DateFormat getDateFormat() {
        DateFormat df = (DateFormat) threadLocal.get();
        if (df == null) {
            df = new SimpleDateFormat(DATE_FORMAT);
            threadLocal.set(df);
        }
        return df;
    }

    public static void main(String[] args) throws ParseException {
        String format = DateUtil.format(new Date());
        System.out.println(format);
        Date parse = DateUtil.parse("2019-12-03 16:02:59");
        System.out.println(parse);
    }
} 
View Code

JDK8中日期函數操作

1. 獲得當前時間,當前時間

        LocalDate localDate = LocalDate.now();
        System.out.println(localDate);//2019-12-03
        Date date = new Date();
        System.out.println(date);//Tue Dec 03 14:49:30 CST 2019

2. 獲得當前毫秒數

    Long millisecond = Instant.now().toEpochMilli();

3.  毫秒數轉日期

LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(1575356644592L), ZoneId.systemDefault());
System.out.println(localDateTime);

4. 日期轉字符串

LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String format = now.format(formatter);
System.out.println(format);//2019-12-03 15:09:38

5. 字符串轉日期

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime parse = LocalDateTime.parse("2019-12-03 13:52:50", dtf);
System.out.println(parse);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM