JDK8 新特性日期時間操作

日期時間操作

// 獲取當前日期
		LocalDate date = LocalDate.now();
		System.out.println("當前日期:" + date);//當前日期:2019-09-17
		// 獲取指定日期
		LocalDate specifyDate = LocalDate.of(2019, 1, 1);
		System.out.println("指定日期:" + specifyDate);//指定日期:2019-01-01
		//獲取年月日信息
	    System.out.printf("年=%d,月=%d, 日=%d", date.getYear(), date.getMonthValue(), date.getDayOfMonth());//年=2019,月=9, 日=17
	    //比較日期是否相等
	    LocalDate now = LocalDate.now();
	    LocalDate s2 = LocalDate.of(2019, 9, 24);
	    System.out.println("日期是否相等=" + now.equals(s2));//日期是否相等=false
	    
	    // 獲取時間 只包含時間,不包括日期
	    LocalTime time = LocalTime.now();
	    System.out.println("當前時間=" + time);//當前時間=14:34:19.484
	    
	    // 當前時間日期計算比較
	    // 時間增量
        LocalTime t1 = LocalTime.now();//當前時間=14:35:51.796
        LocalTime t2 = t1.plusHours(2);
        System.out.println("newTime=" + t2);//newTime=16:35:51.796
        
        // 日期增量
        LocalDate d1 = LocalDate.now(); //當前日期:2019-09-17
        LocalDate d2 = d1.plus(1, ChronoUnit.WEEKS); //新增一週
        LocalDate d3 = d1.plus(1, ChronoUnit.DAYS); // 新增一天
        System.out.println("newDate=" + d2);//newDate=2019-09-24
        System.out.println("newDate=" + d3);//newDate=2019-09-18
        
        // 日期比較
        boolean after = now.isAfter(LocalDate.of(2000, 1, 1));
        System.out.println("日子已經過去了:" + after);
        boolean before = now.isAfter(LocalDate.of(2020, 1, 1));
        System.out.println("2020還未到來:" + before);
        // 獲取時間日期
        LocalDateTime now2 = LocalDateTime.now();
        System.out.println(now2);//2019-09-17T14:46:59.888

日期格式化操作

	// 解析日期
        String dateText = "20190917";
        LocalDate date = LocalDate.parse(dateText, DateTimeFormatter.BASIC_ISO_DATE);
        System.out.println("格式化之後的日期=" + date);
        
        // 格式化日期
        dateText = date.format(DateTimeFormatter.ISO_DATE);
        System.out.println("dateText=" + dateText);
        
        
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String format = now.format(formatter);
        System.out.println(format);//2019-09-17 14:48:28
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章