เปรียบเทียบ Date 2 ตัวใน Swift ใช้เมธอด compare(_:) คืนค่า ComparisonResult
สร้าง Date เพื่อทดสอบ
let calendar = Calendar.current
var components1 = DateComponents(year: 1993, month: 6, day: 5)
var components2 = DateComponents(year: 1995, month: 2, day: 4)
let date1 = calendar.date(from: components1)!
let date2 = calendar.date(from: components2)!
การเปรียบเทียบ
let result = date2.compare(date1)
switch result {
case .orderedAscending:
print("date2 < date1 (date2 มาก่อน)")
case .orderedDescending:
print("date2 > date1 (date2 มาหลัง)")
case .orderedSame:
print("date2 == date1 (วันเวลาเท่ากัน)")
}
// Output: date2 > date1
ComparisonResult Enum
.orderedAscending- ตัวแรก น้อยกว่า (มาก่อน).orderedDescending- ตัวแรก มากกว่า (มาหลัง).orderedSame- เท่ากัน
Operator Overloading (Swift สะดวกกว่า)
if date1 < date2 { print("date1 มาก่อน date2") }
if date1 > date2 { print("date1 มาหลัง date2") }
if date1 == date2 { print("เท่ากัน") }
// รองรับ <=, >= ด้วย
Extension Helper
extension Date {
func isBefore(_ date: Date) -> Bool { return self < date }
func isAfter(_ date: Date) -> Bool { return self > date }
func isSameDay(as date: Date) -> Bool {
return Calendar.current.isDate(self, inSameDayAs: date)
}
}
// ใช้งาน
date1.isBefore(date2) // true
date1.isSameDay(as: date2) // false
การเปรียบเทียบเฉพาะวันที่ (Ignore Time)
let calendar = Calendar.current
if calendar.isDate(date1, inSameDayAs: date2) {
print("วันเดียวกัน")
}
// หรือ Normalize ให้เป็นต้นวัน
let startOfDay1 = calendar.startOfDay(for: date1)
let startOfDay2 = calendar.startOfDay(for: date2)
if startOfDay1 == startOfDay2 { ... }
Time Interval (ความต่างวินาที)
let interval = date2.timeIntervalSince(date1) // วินาที (Double)
let days = interval / 86400
print("ต่างกัน \(Int(days)) วัน")