Date 구조체
Date()
: 지금 현재시점 Date 인스턴스 생성
let now = Date()
let yesterday = now - 86400
Calendar 구조체
- 절대 시점(Date)을 달력의 요소 (연/월/일/요일)로 변환해준다
var calendar = Calendar.current
let year: Int = calendar.component(.year, from: now)
let month: Int = calendar.component(.month, from: now)
let day: Int = calendar.component(.day, from: now)
let timeHour: Int = calendar.component(.hour, from: now)
let timeMinute: Int = calendar.component(.minute, from: now)
let timeSecond: Int = calendar.component(.second, from: now)
let weekday: Int = calendar.component(.weekday, from: now)
let myCal = Calendar.current
var myDateCom = myCal.dateComponents([.year, .month, .day], from: now)
myDateCom.year
myDateCom.month
myDateCom.day
print("\(myDateCom.year!)년 \(myDateCom.month!)월 \(myDateCom.day!)일")
- 날짜와 시간을 원하는 형식의 문자열로 변환하는 방법을 제공하는 클래스
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US")
formatter.timeZone = TimeZone.current
formatter.dateStyle = .full
formatter.timeStyle = .full
let someString1 = formatter.string(from: Date())
print(someString1)
formatter.dateFormat = "yyyy년 MMMM d일 (E)"
let someString2 = formatter.string(from: Date())
print(someString2)
let newFormatter = DateFormatter()
newFormatter.dateFormat = "yyyy/MM/dd"
let someDate = newFormatter.date(from: "2021/07/12")!
print(someDate)
활용 예시
DateComponents
var components = DateComponents()
components.year = 2021
components.month = 1
components.day = 1
components.hour = 12
components.minute = 30
components.second = 0
let specifiedDate: Date = Calendar.current.date(from: components)!
print(specifiedDate)
extension Date {
init?(y year: Int, m month: Int, d day: Int) {
var components = DateComponents()
components.year = year
components.month = month
components.day = day
guard let date = Calendar.current.date(from: components) else {
return nil
}
self = date
}
}
let someDate = Date(y: 2021, m: 1, d: 1)
let someDate2 = Date(y: 2021, m: 7, d: 10)