새소식

iOS/Swift

[Swift] Calendar

  • -

Calendar(struct)

달력 단위와 절대 시점간의 관계를 정의하고, 날짜 계산 및 비교 기능 제공


import Foundation

// 달력 선택
let buddhistCalendar = Calendar(identifier: .buddhist)

let now = Date()
// 사용자의 현재 달력
let calendar = Calendar.current
// 날짜 요소에 접근하기
let year = calendar.component(.year, from: now) // 년(Int)
let month = calendar.component(.month, from: now) // 월(Int)
let day = calendar.component(.day, from: now) // 일(Int)
let weekday = calendar.component(.weekday, from: now) // 요일(Int)
var stringWeekDay: String{ // X요일로 변환, 1(일) ~ 7(토)
    switch(weekday){
        case 1: return "일"
        case 2: return "월"
        case 3: return "화"
        case 4: return "수"
        case 5: return "목"
        case 6: return "금"
        case 7: return "토"
        default: return ""
    }
}
// 현재 날짜 출력
print("\(year)년 \(month)월 \(day)일 \(stringWeekDay)요일") // "2024년 3월 9일 토요일"
// 두 날짜 간의 차이 계산
if let futureDate = calendar.date(byAdding: .day, value: 10, to: now){ // now부터 10일 후의 날짜
    let components = calendar.dateComponents([.day], from: now, to: futureDate)
    if let days = components.day{
        print("현재와 \(days)일 차이가 납니다.")
    }
}
// 날짜에 일정기간 더하기
if let addDate = calendar.date(byAdding: .year, value: 1, to: now){ // now부터 1년 후의 날짜
    let year = calendar.component(.year, from: addDate)
    let month = calendar.component(.month, from: addDate)
    let day = calendar.component(.day, from: addDate)
    print("현재 날짜에서 1년 후의 날짜 : \(year)년 \(month)월 \(day)일")
}

 

 

Calendar | Apple Developer Documentation

A definition of the relationships between calendar units and absolute points in time, providing features for calculation and comparison of dates.

developer.apple.com

 

728x90

'iOS > Swift' 카테고리의 다른 글

[iOS] WKUIDelegate  (0) 2024.03.16
[iOS] WKNavigationDelegate  (0) 2024.03.16
[iOS] WKWebView  (0) 2024.03.03
[Swift] Mirror  (1) 2024.02.18
[iOS] viewIsAppearing(_:)  (0) 2024.01.28
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.