카테고리 없음

Date 값 간 비교

ghnn 2025. 8. 11. 23:16

커뮤니티 뷰를 만들면서 날짜를 계산해야 할 일이 생겼다.

예를 들어 게시글 작성 시간이 현재 시간과 얼마나 차이 나는지 계산해,

“0분 전”, “3시간 전”, “2일 전”과 같이 사용자 친화적인 형태로 표시해야 했다.

 

Swift에서 날짜를 비교하는 방법은 여러 가지가 있으며,

사용하는 API에 따라 계산 정확도와 처리 방식이 달라진다.

이번 TIL에서는 Date 값 간 차이를 구하는 대표적인 세 가지 방법과,

DateComponents에서 값이 nil과 0으로 나오는 차이점을 정리했다.


1. 초 단위 비교  -  timeIntervalSince

Date끼리 빼면 TimeInterval(초 단위 Double)이 나오기 때문에, 이를 분·시간·일 등으로 변환할 수 있다.

let now = Date()
let target = now.addingTimeInterval(4000) // 예: 약 1시간 6분 뒤

let diffInSeconds = target.timeIntervalSince(now) // target - now
let diffInMinutes = Int(diffInSeconds / 60)
let diffInHours = Int(diffInSeconds / 3600)

print(diffInSeconds) // 4000.0
print(diffInMinutes) // 66
print(diffInHours)   // 1

장점

  • 단순하고 빠름
  • 초 단위로 직접 계산 가능

단점

  • 윤년, 월별 일수, 서머타임 등을 직접 고려해야 함

2. 단위별 비교 - Calendar DateComponents

Calendar.dateComponents(_:from:to:)를 사용하면 원하는 단위(.year, .month, .day 등)로 차이를 구할 수 있다.

let calendar = Calendar.current
let fromDate = Date()
let toDate = fromDate.addingTimeInterval(60 * 60 * 24 * 40) // 40일 뒤

let components = calendar.dateComponents([.year, .month, .day], from: fromDate, to: toDate)

print("년: \(components.year)")
print("월: \(components.month)")
print("일: \(components.day)")

// 년: Optional(0)
// 월: Optional(1)
// 일: Optional(10)

 


옵셔널인 이유

DateComponents의 각 프로퍼티는 Int?로 정의돼 있다.

이는 “이 단위를 포함했는지 여부”와 “계산 가능 여부”를 구분하기 위함이다.

 

값이 0이 나오는 계산을 하면 nil이 되는 것이 아님

  • nil → 해당 단위를 계산하지 않거나, 계산 불가능한 경우
  • 0 → 계산은 되었지만 해당 단위 차이가 없는 경우
  • 예: 1년 미만 → .year 값은 Optional(0)
let comp = calendar.dateComponents([.month], from: fromDate, to: toDate)
print(comp.year) // nil (요청하지 않음)

3. 크기 비교 - compare(_:) 메서드

Date에는 두 값을 단순히 이전·같음·이후로 비교하는 메서드도 있다.

let date1 = Date()
let date2 = date1.addingTimeInterval(-100)

switch date1.compare(date2) {
case .orderedAscending:
    print("date1 < date2")
case .orderedSame:
    print("date1 == date2")
case .orderedDescending:
    print("date1 > date2")
}

요약

방법 특징 사용 예시
timeIntervalSince 초 단위 차이 계산, 단순 타이머, 카운트다운
Calendar.dateComponents 단위별 차이 계산, 윤년/서머타임 처리 "n년 m개월 d일 전" 계산
compare(_: ) 순서만 비교 정렬, 조건 분기