JDK8中增加了一系列時間的類,
(據說)是為了干掉過去的Date,Calendar類的,
過去的Date類(據說)有着線程不安全等諸多弊端,
至於我的個人感受就是用起來實在是很麻煩,我一般封裝成幾個常用的方法以后每次就調方法,再也不想看里面是怎么實現的了.
而發現了LocalDateTime這種新類以后,經過我的簡單的試用,覺得完全可以取代掉之前使用時間的一切方法.非常好用,太好用了.
下面是簡單的使用教程:
獲取當前年/月/日
獲取前一天以前是這么干的
public static String getYesterdayByFormat(String timeFormat){ //獲取當前日期 Date date = new Date(); SimpleDateFormat sf = new SimpleDateFormat(timeFormat); //通過秒獲取下一天日期 long time = (date.getTime() / 1000) - 60 * 60 * 24;//秒 date.setTime(time * 1000);//毫秒 String yesterday = sf.format(date).toString(); return yesterday; }
現在可以這樣
public static String getYesterdayByFormat(String timeFormat){ return LocalDateTime.now().plusDays(1).format(DateTimeFormatter.ofPattern(timeFormat)); }