天天看點

JDK1.8新特性—— 新增的日期時間API

目錄

      • 1.日期時間API
      • 2.Instant 時間戳類
      • 3.Duration和Period
      • 4.TemporalAdjuster : 時間校正器,是個接口
      • 5.DateTimeFormatter :解析和格式化日期或時間的類
      • 5.ZonedDate,ZonedTime、ZonedDateTime : 帶時區的時間或日期
      • 6. ZoneID 世界時區類

1.日期時間API

LocalDate、 LocalTime、 LocalDateTime類的執行個體是不可變的對象,

分别表示使用 ISO-8601月曆系統的日期、時間、日期和時間。

它們提供了簡單的日期或時間,并不包含目前的時間資訊。也不包含與時區相關的資訊。

注: ISO-8601月曆系統是國際标準化組織制定的現代公民的日期和時間的表示法

這些新增的日期時間API都在 java.time包下

擷取對象的方法
	方式1通過靜态方法  now();
		例如:LocalDateTime ldt = LocalDateTime.now();

	方式2通過靜态方法of()方法參數可以指定年月日時分秒
		例如:LocalDateTime of = LocalDateTime.of(2018, 12, 30, 20, 20, 20);
           
常用方法
	1.與擷取相關的方法:get系類的方法
		ldt.getYear();擷取年
		ldt.getMinute();擷取分鐘
		ldt.getHour();擷取小時
		getDayOfMonth 獲得月份天數(1-31)
		getDayOfYear 獲得年份天數(1-366)
		getDayOfWeek 獲得星期幾(傳回一個 DayOfWeek枚舉值)
		getMonth 獲得月份, 傳回一個 Month 枚舉值
		getMonthValue 獲得月份(1-12)
		getYear 獲得年份
	2.格式化日期日期字元串的方法 format()
		例如:String yyyy = ldt.format(DateTimeFormatter.ofPattern("yyyy"));
	3.轉換的方法 toLocalDate();toLocalTime();
		例如:LocalDate localDate = ldt.toLocalDate();
		例如:LocalTime localTime = ldt.toLocalTime();
	4.判斷的方法
		isAfter()判斷一個日期是否在指定日期之後
		isBefore()判斷一個日期是否在指定日期之前
		isEqual(); 判斷兩個日期是否相同
		isLeapYear()判斷是否是閏年注意是LocalDate類中的方法
			例如:  boolean after = ldt.isAfter(LocalDateTime.of(2024, 1, 1, 2, 3));
			例如  boolean b= LocalDate.now().isLeapYear();

	5.解析的靜态方法parse("2007-12-03T10:15:30");
		paser() 将一個日期字元串解析成日期對象,注意字元串日期的寫法的格式要正确,否則解析失敗
			例如:LocalDateTime parse = LocalDateTime.parse("2007-12-03T10:15:30");
		按照我們指定的格式去解析:
		
		注意細節:如果用LocalDateTime 想按照我們的自定義的格式去解析,注意
		日期字元串的 年月日時分秒要寫全,不然就報錯
			LocalDateTime ldt4 = LocalDateTime.now();
			DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
			LocalDateTime.parse("2018-01-21 20:30:36", formatter2);

	6.添加年月日時分秒的方法 plus系列的方法 都會傳回一個新的LocalDateTime的對象
		LocalDateTime localDateTime = ldt.plusYears(1);
		LocalDateTime localDateTime1 = ldt.plusMonths(3);
		LocalDateTime localDateTime2=ldt.plusHours(10);
	7.減去年月日時分秒的方法 minus 系列的方法 注意都會傳回一個新的LocalDateTime的對象
		例如:LocalDateTime localDateTime2 = ldt.minusYears(8);
	8.指定年月日時分秒的方法 with系列的方法 注意都會傳回一個新的LocalDateTime的對象
		例如 LocalDateTime localDateTime3 = ldt.withYear(1998);
		  //擷取這個月的第幾個星期幾是幾号,比如 TemporalAdjusters.dayOfWeekInMonth(2, DayOfWeek.FRIDAY) 代表的意思是這個月的第二個星期五是幾号
 			  // TemporalAdjusters.dayOfWeekInMonth(2, DayOfWeek.FRIDAY)
  			  LocalDateTime with1 = now.with(TemporalAdjusters.dayOfWeekInMonth(2,DayOfWeek.FRIDAY));
           

2.Instant 時間戳類

從1970-01-01 00:00:00 截止到目前時間的毫秒值;

1擷取對象的方法 now()
	注意預設擷取出來的是目前的美國時間和我們相差八個小時
		Instant ins = Instant.now();
		System.out.println(ins);
		我們在東八區 是以可以加8個小時 就是我們的中原標準時間
2. Instant中設定偏移量的方法:atOffset() 設定偏移量
		OffsetDateTime time = ins.atOffset(ZoneOffset.ofHours(8));
		System.out.println(time);
3.擷取系統預設時區時間的方法atZone()
	方法的參數是要一個時區的編号可以通過時區編号類擷取出來
		ZoneId.systemDefault()擷取本地的預設時區ID
		ZonedDateTime zonedDateTime = ins.atZone(ZoneId.systemDefault());
		System.out.println(zonedDateTime);
4.get系列的方法

	getEpochSecond() 擷取從1970-01-01 00:00:00到目前時間的秒值
	toEpochMilli();擷取從1970-01-01 00:00:00到目前時間的毫秒值
	getNano()方法是把擷取到的目前時間的秒數 換算成納秒
	long epochSecond = ins.getEpochSecond();//擷取從1970-01-01 00:00:00到目前時間的秒值
	getNano()方法是把擷取到的目前時間的豪秒數 換算成納秒 比如目前時間是2018-01-01 14:00:20:30
	那就把30豪秒換算成納秒 int nano = ins.getNano();
5. ofEpochSecond()方法 給計算機元年增加秒數
	ofEpochMilli() 給計算機元年增加毫秒數
	例如 Instant instant = Instant.ofEpochSecond(5);
		 System.out.println(instant);
		機關換算
		 0.1 毫秒 = 10 的5次方納秒 = 100000 納秒
   		1 毫秒 = 1000 微妙 = 1000000 納秒
           

3.Duration和Period

Duration : 用于計算兩個“時間”間隔的類

Period : 用于計算兩個“日期”間隔的類

Duration類中靜态方法between()
	Instant start = Instant.now();
		for(int i=0;i<1000L;i++){
			System.out.println("循環内容");
		}
	Instant end = Instant.now();
	靜态方法:between() 計算兩個時間的間隔,預設是秒
	Duration between = Durati’on.between(start, end);
	Duration中的toMillis()方法:将秒轉成毫秒
	System.out.println(between.toMillis());

Period類 中的靜态方法between()
	計算兩個日期之間的間隔
	LocalDate s = LocalDate.of(1985, 03, 05);
	LocalDate now = LocalDate.now();
	Period be = Period.between(s, now);
	System.out.println(be.getYears());間隔了多少年
	System.out.println(be.getMonths());間隔了多少月
	System.out.println(be.getDays());間隔多少天
           

Duration的計算時間間隔案例

須使用Duration中的靜态方法between()。

public class Test {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime of = LocalDateTime.of(2000, 5, 8, 7, 20, 30);
        Duration between = Duration.between(of, now);
        System.out.println(between.toMillis());
    }
}
           

Period計算時間間隔案例

public class Test2 {
    public static void main(String[] args) {
        LocalDate now = LocalDate.now();
        LocalDate of = LocalDate.of(2000, 5, 8);
        Period between = Period.between(of, now);
        System.out.println(between.toTotalMonths());
    }
}
           

4.TemporalAdjuster : 時間校正器,是個接口

一般我們用該接口的一個對應的工具類 TemporalAdjusters中的一些常量,來指定日期

例如:
LocalDate now = LocalDate.now();
    System.out.println(now);
1 使用TemporalAdjusters自帶的常量來設定日期
	LocalDate with = now.with(TemporalAdjusters.lastDayOfYear());
	System.out.println(with);
2 采用TemporalAdjusters中的next方法來指定日期
	 LocalDate date = now.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
	 System.out.println(date);
	例如:TemporalAdjusters.next(DayOfWeek.SUNDAY) 本周的星期天
	例如:TemporalAdjusters.nextOrSame(DayOfWeek.MONDAY) 下一周的星期一
3 采用自定義的方式來指定日期 比如指定下個工作日
	 LocalDateTime ldt = LocalDateTime.now();
	LocalDateTime workDay = ldt.with(new TemporalAdjuster() {
		@Override
	 public Temporal adjustInto(Temporal temporal) {
		 //向下轉型
		 LocalDateTime ld = (LocalDateTime) temporal;
		 //擷取這周的星期幾
		 DayOfWeek dayOfWeek = ld.getDayOfWeek();
	 if (dayOfWeek.equals(DayOfWeek.FRIDAY)) {
			 return ld.plusDays(3);//如果這天是星期五,那下個工做日就加3天
		} else if (dayOfWeek.equals(DayOfWeek.SATURDAY)) {
			return ld.plusDays(2);//如果這天是星期六,那下個工做日就加2天
		} else {
			//其他就加一天
			return ld.plusDays(1);
	 }
        }
    });

    System.out.println(workDay);
           

5.DateTimeFormatter :解析和格式化日期或時間的類

1.擷取對象的方式,通過靜态方法ofPattern("yyyy-MM-dd");
	DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
	LocalDateTime now = LocalDateTime.now();
2.format()方法把一個日期對象的預設格式 格式化成指定的格式
	String format1 = dateFormat.format(now);
	System.out.println(format1);
3.格式化日期 方式2使用日期類中的format方法 傳入一個日期格式化類對象

	LocalDateTime now1 = LocalDateTime.now();
	使用日期類中的format方法 傳入一個日期格式化類對象
	使用DateTimeFormatter中提供好的日期格式常量
	now1.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
4.使用自定義的日期格式格式化字元串
	DateTimeFormatter timeFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");//自定義一個日期格式
	String time = now1.format(timeFormat);
	System.out.println(time);

5. 把一個日期字元串轉成日期對象
	使用日期類中的parse方法傳入一個日期字元串,傳入對應的日期格式化類
	DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
	LocalDateTime parse = LocalDateTime.parse(time, timeFormat);
	System.out.println(parse);
           

5.ZonedDate,ZonedTime、ZonedDateTime : 帶時區的時間或日期

用法和 LocalDate、 LocalTime、 LocalDateTime 一樣 隻不過ZonedDate,ZonedTime、ZonedDateTime 這三個帶有目前系統的預設時區

6. ZoneID 世界時區類

1.擷取世界各個地方的時區的集合 的方法getAvailableZoneIds()
		使用ZoneID中的靜态方法getAvailableZoneIds();來擷取
			例如:Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();
	2.擷取系統預設時區的ID
		ZoneId zoneId = ZoneId.systemDefault(); //Asia/Shanghai
	3.擷取帶有時區的日期時間對象
		//建立日期對象
		LocalDateTime now = LocalDateTime.now();
		//擷取不同國家的日期時間根據各個地區的時區ID名建立對象
		ZoneId timeID = ZoneId.of("Asia/Shanghai");
		//根據時區ID擷取帶有時區的日期時間對象
		ZonedDateTime time = now.atZone(timeID);
		System.out.println(time);
		//方式2 通過時區ID 擷取日期對象
		LocalDateTime now2 = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
		System.out.println(now2);