[iOS] Calendar와 DateComponents로 날짜 다루기

Calendar에는 여러 종류의 달력이 있어서 우리가 원하는 달력을 Identifier 속성을 사용해서 정해주거나 current 속성으로 아이폰에 설정되있는 달력을 사용한다. Identifier 속성은 열거형이고 어떤 속성이 있는지 공식문서 https://developer.apple.com/documentation/foundation/calendar/identifier 를 참고하면 좋다.

Calendar.Identifier.buddhist
Calendar.current



새로운 날짜 만들기


DateComponents 인스턴스를 만들어서 새로운 날짜를 만들고 날짜 계산을 할 수 있다. 날짜뿐만 아니라 시분초 다양하게 가능하다. TimeInteval로도 가능은 하지만 매번 시간차 계산을 해야하기 떄문에 번거롭다.

let calendar = Calendar.current
var components = DateComponents()
components.day = 28
components.month = 2
components.year = 2020

let specialDay = calendar.date(from: components)
// "Feb 28, 2020 at 12:00 AM"

DateComponents() 만들기 -> 원하는 날짜 설정 -> date로 변환


날짜 계산


날짜 계산할 때 주의해야 할 점은 시간이다. 이유는 예를 들어서 2시간 뒤의 날짜를 계산한다고 하면 22시의 2시간 뒤는 다음날이 되고 그 전의 시간들의 2시간 뒤는 아직 똑같은 날이기 때문이다. 그래서 시간을 포함시킬지 말지 정하고 날짜 계산을 해야한다.

startOfDay를 사용하면 시간을 0시로 바꿀 수 있다.
기준이 되는 날짜부터 더하거나 빼서 그 날짜가 언제인지 구하는 방법은 byAdding 파라미터를 받는 date 메서드를 사용하면 된다.

let calendar = Calendar.current

let now = Date() // "May 16, 2021 at 1:55 PM"

let today = calendar.startOfDay(now) // "May 16, 2021 at 12:00 AM"

var components = DateComponents()
components.day = 18

calendar.date(byAdding: components, to: now)
// "Jun 3, 2021 at 1:55 PM"



특정 날짜부터 오늘까지의 얼마나 차이나는지 계산도 가능하다.

let now = Date()  // "May 16, 2021 at 1:55 PM"

let calendar = Calendar.current

var components = DateComponents()
components.day = 28
components.month = 2
components.year = 2020
let specialDay = calendar.date(from: components)

components = calendar.dateComponents([.month], from: specialDay!, to: now)
components.month // 14

dateComponents의 첫번째 파라미터에 내가 확인하고 싶은 DateComponents의 month를 넣었는데 day나 다른 값들을 Set안에 넣을 수 있다.