Java8 時間API
生活随笔
收集整理的這篇文章主要介紹了
Java8 時間API
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
java.time 包是在JDK8新引入的,提供了用于日期、時間、實例和周期的主要API。
所有類都是不可變的、線程安全的。
import java.time.*; import java.time.format.DateTimeFormatter;public class DateTest {public static void main(String[] args) {LocalDate localDate = LocalDate.now();System.out.println("當前日期: " + localDate);//獲取年、月、日System.out.println("年份: " + localDate.getYear());System.out.println("月份: " + localDate.getMonthValue());System.out.println("日期: " + localDate.getDayOfMonth());System.out.println(localDate.getYear() + "年第" + localDate.getDayOfYear() + "年");System.out.println("星期: " + localDate.getDayOfWeek());System.out.println("判斷當前年份是否是閏年:" + localDate.isLeapYear());//創建時間對象LocalDate lastTime = localDate.of(2008, 8, 8);System.out.println(lastTime);//LocalDate 轉 StringDateTimeFormatter rule = DateTimeFormatter.ofPattern("yyyy-MM-dd");String timeStr = lastTime.format(rule);System.out.println(timeStr);//String 轉 LocalDateLocalDate lastTime1 = localDate.parse(timeStr);System.out.println(lastTime1);LocalDateTime now = LocalDateTime.now();System.out.println(now.getYear() + "年" + now.getMonthValue() + "月" + now.getDayOfMonth() + "日 時間:"+ now.getHour() + ":" //時+ now.getMinute() + ":" //分+ now.getSecond() + ":" //秒+ now.getNano()); //毫秒//增加年份 返回新的對象LocalDateTime nextYear = now.plusYears(1);System.out.println(nextYear);//增加月份 返回新的對象LocalDateTime nextMonth = nextYear.plusMonths(1);System.out.println(nextMonth);//增加天數 返回新的對象 LocalDateTime nextDay = nextMonth.plusDays(2);System.out.println(nextDay);//增加小時數 返回新的對象LocalDateTime nextHours = nextDay.plusHours(2);System.out.println(nextHours);//nextHours.plusMinutes(minutes)//nextHours.plusSeconds(seconds)//nextHours.plusNanos(nanos)//不一一演示//減去年份LocalDateTime preYear = nextHours.minusYears(1);System.out.println(preYear);//減去月份LocalDateTime preMonth = preYear.minusMonths(1);System.out.println(preMonth);//減去日期LocalDateTime preDay = preMonth.minusDays(2);System.out.println(preDay);//設置時間//設置年份LocalDateTime setYear = preDay.withYear(1997);System.out.println(setYear);//設置月份LocalDateTime setMonth = setYear.withMonth(5);System.out.println(setMonth);LocalDateTime dateTime = LocalDateTime.parse("2010-01-01T19:24:01.078");System.out.println("String 轉 LocalDateTime: " + dateTime);DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");System.out.println("LocalDateTime 轉 String: " + dateTime.format(formatter));//java.time.Duration 計算時間LocalDateTime start = LocalDateTime.of(1997, 7, 3, 1, 1);LocalDateTime end = LocalDateTime.of(2020, 1, 1, 1, 1);Duration result = Duration.between(start, end);System.out.println("距離天數: " + result.toDays()); //沒有距離年數的方法System.out.println("距離小時數: " + result.toHours());System.out.println("距離分鐘數: " + result.toMinutes());System.out.println("距離秒數: " + result.toMillis()); //秒}}
轉載于:https://www.cnblogs.com/mxh-java/p/11523598.html
總結
以上是生活随笔為你收集整理的Java8 時間API的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring学习(五)bean装配详解之
- 下一篇: Spring学习(六)bean装配详解之