一、新的Date API介绍
LocalDate
LocalTime
Instant
Duration
Period
formater
parsejdk以前的java.util.Date存在的问题
1)比如new Date(119, 2, 18)表示Mon Mar 18 00:00:00 CST 2019,2019年3月18日,year要从1900年加起,month是从0开始,day是从1开始。
2)SimpleDateFormat不是线程安全的,比如多线程情况下simpleDateFormat.parse会出问题。
3)Date名字叫日期,但是后面还有time时间
例子如下:
1 package com.cy.java8; 2 3 import java.text.ParseException; 4 import java.text.SimpleDateFormat; 5 import java.util.Date; 6 7 public class DateTest { 8 9 public static void main(String[] args) throws ParseException {10 Date date = new Date(119, 2, 18);11 System.out.println(date);12 13 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");14 for(int i=0; i<5; i++){15 new Thread(()->{16 try {17 Date parseDate = sdf.parse("20190505");18 System.out.println(parseDate);19 } catch (ParseException e) {20 e.printStackTrace();21 }22 23 }).start();24 }25 }26 }
二、LocalDate
1 package com.cy.java8; 2 3 import java.time.LocalDate; 4 import java.time.temporal.ChronoField; 5 6 public class DateTest { 7 8 public static void main(String[] args) { 9 testLocalDate();10 }11 12 /**13 * LocalDate是线程安全的14 */15 private static void testLocalDate(){16 LocalDate localDate = LocalDate.of(2019, 10, 2);17 System.out.println(localDate.getYear());18 System.out.println(localDate.getMonth());19 System.out.println(localDate.getMonthValue());20 System.out.println(localDate.getDayOfYear());21 System.out.println(localDate.getDayOfMonth());22 System.out.println(localDate.getDayOfWeek());23 24 System.out.println(localDate.get(ChronoField.YEAR));25 System.out.println(localDate.get(ChronoField.MONTH_OF_YEAR));26 System.out.println(localDate.get(ChronoField.DAY_OF_MONTH));27 28 LocalDate now = LocalDate.now();29 System.out.println(now);30 }31 }
console:
2019OCTOBER102752WEDNESDAY20191022019-10-02
三、
----