คลาส LocalDateTime (Java 8+) แทนวันที่และเวลารวมกัน ไม่มี time zone ใช้เมธอด isBefore(), isAfter(), isEqual() เปรียบเทียบได้
ตัวอย่างที่ 1: ใช้ LocalDateTime (แนะนำ)
import java.time.LocalDateTime;
public class Test {
public static void main(String args[]) {
// of(year, month, day, hour, minute, second)
LocalDateTime dateTime1 = LocalDateTime.of(2007, 11, 25, 10, 15, 45);
LocalDateTime dateTime2 = LocalDateTime.of(1999, 9, 12, 7, 25, 55);
if (dateTime1.isAfter(dateTime2)) {
System.out.println(dateTime1 + " is after " + dateTime2);
} else if (dateTime1.isBefore(dateTime2)) {
System.out.println(dateTime1 + " is before " + dateTime2);
} else {
System.out.println(dateTime1 + " is equal to " + dateTime2);
}
}
}
ผลลัพธ์
2007-11-25T10:15:45 is after 1999-09-12T07:25:55
ตัวอย่างที่ 2: ใช้ SimpleDateFormat + Date (Legacy)
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CreateDateTime {
public static void main(String args[]) throws ParseException {
String dateTimeStr1 = "26-09-1989 8:27:45";
String dateTimeStr2 = "12-11-2010 2:30:12";
// รูปแบบ: dd-MM-yyyy HH:mm:ss
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Date dateTime1 = formatter.parse(dateTimeStr1);
Date dateTime2 = formatter.parse(dateTimeStr2);
if (dateTime1.after(dateTime2)) {
System.out.println(dateTimeStr1 + " is after " + dateTimeStr2);
} else if (dateTime1.before(dateTime2)) {
System.out.println(dateTimeStr1 + " is before " + dateTimeStr2);
} else {
System.out.println(dateTimeStr1 + " is equal to " + dateTimeStr2);
}
}
}
ผลลัพธ์
26-09-1989 8:27:45 is before 12-11-2010 2:30:12
ตัวอย่างที่ 3: ใช้ LocalDateTime.parse() กับ DateTimeFormatter
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateTimeCompare {
public static void main(String args[]) {
String dt1 = "2024-01-15T10:30:00";
String dt2 = "2024-01-15T14:45:00";
// ISO format ไม่ต้องระบุ formatter
LocalDateTime ldt1 = LocalDateTime.parse(dt1);
LocalDateTime ldt2 = LocalDateTime.parse(dt2);
System.out.println(ldt1.isBefore(ldt2) ? "dt1 ก่อน dt2" : "dt1 หลังหรือเท่ากับ dt2");
}
}
สรุปการเลือกใช้
| สถานการณ์ | คลาสที่แนะนำ | เหตุผล |
|---|---|---|
| วันที่อย่างเดียว | LocalDate | เรียบง่าย ไม่มี time zone |
| เวลาอย่างเดียว | LocalTime | เรียบง่าย ไม่มี time zone |
| วันที่+เวลา (ไม่มี TZ) | LocalDateTime | รวมทั้งคู่ immutable, thread-safe |
| วันที่+เวลา+Time Zone | ZonedDateTime | รองรับ DST, offset |
| Timestamp (UTC) | Instant | จุดบน timeline แบบ absolute |
⚠️ ข้อควรระวัง
- LocalDateTime ไม่มี time zone - เหมาะสำหรับ "local" time เช่น นัดหมายในพื้นที่
- ต้องการเปรียบเทียบข้าม time zone ใช้ ZonedDateTime หรือแปลงเป็น Instant ก่อน
- Legacy Date/Calendar mutable และไม่ thread-safe