Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách triển khai java.time.LocalDate dùng JShell trong Java 9?

JShell là công cụ REPL (Read-Eval-Print-Loop) tương tác giới thiệu trong Java 9 nhận input, đánh giá và trả output cho user.

Lớp java.time.LocalDate cung cấp nhiều phương thức lấy thông tin Date: Ngày/Tháng/Năm và thuộc tính liên quan; meta-thông tin Date: thông tin phân loại như năm nhuận... LocalDate class immutable, dùng các phương thức cung cấp để cộng/trừ ngày, tháng, năm. Mỗi phương thức trả về instance LocalDate mới.

Hai đoạn mã dưới in các operation khác nhau dùng LocalDate class.

Đoạn mã 1

jshell> import java.time.*;
jshell> LocalDate today = LocalDate.now()
today ==> 2020-04-22
jshell> today.getYear()
$3 ==> 2020
jshell> today.getDayOfWeek()
$4 ==> WEDNESDAY
jshell> today.getDayOfMonth()
$5 ==> 22
jshell> today.getDayOfYear()
$6 ==> 113
jshell> today.getMonth()
$7 ==> APRIL
jshell> today.getMonthValue()
$8 ==> 4
jshell> today.isLeapYear()
$9 ==> true
jshell> today.lengthOfYear()
$10 ==> 366
jshell> today.lengthOfMonth()
$11 ==> 30

Đoạn mã 2

jshell> today.plusDays(50)
$12 ==> 2020-06-11
jshell> today.plusMonths(50)
$13 ==> 2024-06-22
jshell> today.plusYears(50)
$14 ==> 2070-04-22
jshell> today.minusYears(50)
$15 ==> 1970-04-22
jshell> LocalDate yesterYear = today.minusYears(50)
yesterYear ==> 1970-04-22
jshell> today
today ==> 2020-04-22