說到java中的Date,大部分人應該都用過,我見到的項目中也都是使用Date(加上Calendar)來處理各種時間日期的。所以並沒有對這個類產生過什麼想法,後來看到有人推薦使用LocalDateTime來處理,然後看了下Date相關的一些使用,發現還有隱藏着一些問題的。
說到Date就不能不再說一下DateFormat,因爲Date輸出的日期(Fri Oct 25 10:01:03 CST 2019)可讀性很差,所以必須進行格式化,轉化成易讀的日期格式,那麼DateFormat就來了。
//Date轉String
Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = df.format(date);
//String轉Date
String dateStr = "2019-10-25 10:00:00";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = df.parse(dateStr);
上面的時間轉換看起來很簡單,但是這裏面還隱藏着問題。SimpleDateFormat是線程不安全的,來看一下format()的源碼
private StringBuffer format(Date date, StringBuffer toAppendTo,
FieldDelegate delegate) {
// Convert input date to time field list
calendar.setTime(date);
boolean useDateFormatSymbols = useDateFormatSymbols();
......
看到這個方法的第一行 calendar.setTime(date),就會發現,calendar是在DateFormat類中的一個變量,並且沒有做線程安全控制。如用static修飾的SimpleDateFormat調用format方法,多線程情況下,可能一個線程剛設置了time,另一個線程馬上又修改了time,就會導致返回的時間錯誤。SimpleDateFormat的parse()方法同樣也存在問題。
當然如果我們每次使用的時候都new一個SimpleDateFormat對象是可以避免上面那種情況的。只不過多次創建和銷燬對象的開銷會變大。
此時重點來了,jdk1.8中新提供了幾個類:LocalDate、LocalTime、LocalDateTime。
public static void main(String[] args) throws ParseException{
//年月日
LocalDate localDate = LocalDate.now();
System.out.println(localDate);
System.out.println(localDate.getYear()+"-"+localDate.getMonthValue()+
"-"+localDate.getDayOfMonth());
//時分秒
LocalTime localTime = LocalTime.now();
System.out.println(localTime);
System.out.println(localTime.getHour()+":"+localTime.getMinute()+
":"+localTime.getSecond());
//年月日時分秒
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDateTime);
System.out.println(localDateTime.getYear()+"-"+localDateTime.getMonthValue()+
"-"+localDateTime.getDayOfMonth()+" "+localDateTime.getHour()+
":"+localDateTime.getMinute()+":"+localDateTime.getSecond());
//創建指定日期
LocalDate localDate1 = LocalDate.of(2019, 10, 10);
//解析字符串創建
LocalDate date = LocalDate.parse("2018-10-31");
LocalTime time = LocalTime.parse("13:45:20");
//合併日期和時間
LocalDateTime localDateTime1 = LocalDateTime.of(date,time);
//修改日期
LocalDate localDate2 = LocalDate.of(2018, 10, 31);//2018-10-31
LocalDate localDate3 = localDate2.withYear(2011);//2011-10-31
LocalDate localDate4 = localDate2.withDayOfMonth(25);//2011-10-25
//自定義格式化
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//String和LocalDateTime互轉
String s1 = localDateTime1.format(dateTimeFormatter);
LocalDateTime localDateTime2 = LocalDateTime.parse("2019-10-25 15:15:01",dateTimeFormatter);
}
上面列了一部分的用法,當然還有很多用法可以通過查閱文檔去了解一下