(1) UTC 기준
(2) 유닉스 기준
let now = Date()
print(now) // UTC 기준 시간 > yyyy-MM-dd HH:mm:ss +0000
let oneSecond = TimeInterval(1.0)
var calendar = Calendar.current
calendar.locale // 달력의 지역 (영어/한국어)
calendar.timeZone // 타임존 => Asia/Seoul
calendar.locale = Locale(identifier: "ko_KR")
// 1) 날짜 - 년 / 월 / 일
let year: Int = calendar.component(.year, from: now)
let month: Int = calendar.component(.month, from: now)
let day: Int = calendar.component(.day, from: now)
// 2) 시간 - 시 / 분 / 초
let timeHour: Int = calendar.component(.hour, from: now)
let timeMinute: Int = calendar.component(.minute, from: now)
let timeSecond: Int = calendar.component(.second, from: now)
// 3) 요일
let weekday: Int = calendar.component(.weekday, from: now)
// 일요일 - 1
// 월요일 - 2
// 화요일 - 3
// ...
// 토요일 - 7
let myCal = Calendar.current
var myDateCom = myCal.dateComponents([.year, .month, .day], from: now)
print("\(myDateCom.year!)년 \(myDateCom.month!)월 \(myDateCom.day!)일")
날짜와 시간을 원하는 형식의 문자열(String)으로 변환하는 방법을 제공하는 클래스
let formatter = DateFormatter()
// 나라 / 지역마다 날짜와 시간을 표시하는 형식과 언어가 다름
formatter.locale = Locale(identifier: "ko_KR")
formatter.timeZone = TimeZone.current
// (1) 날짜 형식 선택
formatter.dateStyle = .full // "Tuesday, April 13, 2021"
formatter.dateStyle = .long // "April 13, 2021"
formatter.dateStyle = .medium // "Apr 13, 2021"
formatter.dateStyle = .none // (날짜 없어짐)
formatter.dateStyle = .short // "4/13/21"
// (2) 시간 형식 선택
formatter.timeStyle = .full // "2:53:12 PM Korean Standard Time"
formatter.timeStyle = .long // "2:54:52 PM GMT+9"
formatter.timeStyle = .medium // "2:55:12 PM"
formatter.timeStyle = .none // (시간 없어짐)
formatter.timeStyle = .short // "2:55 PM"
// 실제 변환하기 (날짜 + 시간) ===> 원하는 형식
let someString1 = formatter.string(from: Date())
print(someString1)
let newFormatter = DateFormatter()
newFormatter.dateFormat = "yyyy/MM/dd"
let someDate = newFormatter.date(from: "2021/07/12")!
print(someDate)
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)!
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 // 날짜 생성할 수 없다면 nil리턴
}
self = date //구조체이기 때문에, self에 새로운 인스턴스를 할당하는 방식으로 초기화가능
}
}
let someDate = Date(y: 2021, m: 1, d: 1) // 특정날짜(시점) 객체 생성
let someDate2 = Date(y: 2021, m: 7, d: 10)