Java 8 นำ API ใหม่สำหรับวันที่และเวลาใน package java.time มาให้ 3 คลาสหลักคือ LocalDate, LocalTime, และ LocalDateTime ซึ่งเป็น immutable และ thread-safe มาดูวิธีใช้งานกันครับ
ดึงวันที่ปัจจุบัน (LocalDate)
import java.time.LocalDate;
public class GetCurrentDate {
public static void main(String[] args) {
LocalDate now = LocalDate.now();
System.out.println(now); // 2024-01-15
}
}
จัดรูปแบบวันที่ด้วย DateTimeFormatter
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class GetCurrentDate {
public static void main(String[] args) {
LocalDate now = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
System.out.println(now.format(formatter)); // 2024/01/15
}
}
ดึงรายละเอียดวันที่เพิ่มเติม
import java.time.LocalDate;
public class GetCurrentDate {
public static void main(String[] args) {
LocalDate now = LocalDate.now();
System.out.println("วันนี้: " + now);
System.out.println("วันในสัปดาห์: " + now.getDayOfWeek()); // MONDAY
System.out.println("วันในเดือน: " + now.getDayOfMonth()); // 15
System.out.println("วันในปี: " + now.getDayOfYear()); // 15
System.out.println("เดือน: " + now.getMonth()); // JANUARY
System.out.println("ปี: " + now.getYear()); // 2024
}
}
ดึงเวลาปัจจุบัน (LocalTime)
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class GetCurrentTime {
public static void main(String[] args) {
LocalTime now = LocalTime.now();
System.out.println("เวลาปัจจุบัน: " + now); // 14:30:45.123
System.out.println("จัดรูปแบบ: " + now.format(DateTimeFormatter.ofPattern("HH:mm:ss"))); // 14:30:45
}
}
ดึงรายละเอียดเวลาเพิ่มเติม
import java.time.LocalTime;
public class GetCurrentTime {
public static void main(String[] args) {
LocalTime now = LocalTime.now();
System.out.println("ชั่วโมง: " + now.getHour()); // 14
System.out.println("นาที: " + now.getMinute()); // 30
System.out.println("วินาที: " + now.getSecond()); // 45
System.out.println("ไมโครวินาที: " + now.getNano()); // 123000000
}
}
ดึงวันที่และเวลาร่วมกัน (LocalDateTime)
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class GetCurrentDateTime {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd - HH:mm:ss");
System.out.println(now.format(formatter)); // 2024/01/15 - 14:30:45
// ดึงส่วนประกอบต่างๆ ได้เหมือน LocalDate และ LocalTime
System.out.println("วันในเดือน: " + now.getDayOfMonth());
System.out.println("ชั่วโมง: " + now.getHour());
}
}
สรุป
| คลาส | ใช้สำหรับ | เมธอดหลัก |
|---|---|---|
| LocalDate | วันที่อย่างเดียว | now(), getDayOfMonth(), getMonth(), getYear() |
| LocalTime | เวลาอย่างเดียว | now(), getHour(), getMinute(), getSecond() |
| LocalDateTime | วันที่และเวลา | now(), รวมเมธอดของทั้งสองคลาสข้างต้น |
เคล็ดลับ: สำหรับแอปพลิเคชันที่ต้องการ timezone ให้ใช้
ZonedDateTimeหรือOffsetDateTimeแทน