Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีใช้ java.time.LocalDate ใน JShell Java 9

JShell เป็น REPL (Read-Eval-Print-Loop) interactive tool ใน Java 9 รับ input ประเมินผลคืน output ให้ user

java.time.LocalDate class มีเมธอดมากมายสำหรับดึงข้อมูลวันที่: Day/Month/Year และ attributes ที่เกี่ยวข้อง Date meta-information: ข้อมูล classification เช่น leap year เป็นต้น LocalDate class เป็น immutable ใช้เมธอดต่างๆ add และ subtract days, months, years แต่ละเมธอดคืน instance ใหม่ของ LocalDate

Snippet 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

Snippet 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  // ต้นฉบับไม่เปลี่ยน (immutable)

LocalDate Methods สำคัญ

Category Methods
Getting values getYear(), getMonth(), getMonthValue(), getDayOfMonth(), getDayOfWeek(), getDayOfYear()
Checking isLeapYear(), isBefore(), isAfter(), isEqual()
Length info lengthOfMonth(), lengthOfYear()
Plus (add) plusDays(), plusWeeks(), plusMonths(), plusYears(), plus(TemporalAmount)
Minus (subtract) minusDays(), minusWeeks(), minusMonths(), minusYears(), minus(TemporalAmount)
With (modify) withYear(), withMonth(), withDayOfMonth(), withDayOfYear(), with(TemporalAdjuster)
Static factories now(), of(year, month, day), ofEpochDay(), parse(CharSequence)

ตัวอย่างเพิ่มเติม

jshell> LocalDate christmas = LocalDate.of(2024, 12, 25)
christmas ==> 2024-12-25

jshell> christmas.getDayOfWeek()
$ ==> WEDNESDAY

jshell> LocalDate firstDayOfMonth = christmas.withDayOfMonth(1)
firstDayOfMonth ==> 2024-12-01

jshell> LocalDate nextFriday = christmas.with(java.time.temporal.TemporalAdjusters.next(java.time.DayOfWeek.FRIDAY))
nextFriday ==> 2024-12-27

jshell> Period period = Period.between(today, christmas)
period ==> P8M3D  // 8 months 3 days

jshell> long daysUntil = today.until(christmas, java.time.temporal.ChronoUnit.DAYS)
daysUntil ==> 247

LocalDate vs LocalDateTime vs ZonedDateTime

Class Components Use Case
LocalDate Year, Month, Day Birthday, anniversary, date-only
LocalTime Hour, Minute, Second, Nano Alarm time, opening hours
LocalDateTime Date + Time (no zone) Local appointments, logs
ZonedDateTime Date + Time + Zone Global events, timestamps
Instant Epoch nanoseconds (UTC) Machine timestamps, logging