UTC(Coordinated Universal Time): 국제 표준시간 / 국제 사회가 사용하는 과학적 시간의 표준
- GMT와 같다
- 영국의 그리니치 천문대의 시간을 기준으로 하는 시간
한국의 시간(KST)은 UTC + 9와 같다.
날짜와 시간 데이터를 가지고 놀기 위해선 아래와 같은 요소를 알아야한다.
Date,TimeInterval, Calendar, DateComponents
Date구조체는 초를 기준으로하는 절대적 시점을 의미한다 이를 잘 활용하기 위해선 Calendar이나 DateFormatter를 잘 활용해야한다.
💥1. Date구조체
ReferenceDate: 기준시간 2001.01.01: 00:00:00 UTC를 기준으로 한다.
var now = Date() //현재
var yesterday = now - 86400 //어제
var tomorrow = Date(timeIntervalSinceNow: 86400) //내일
- Reference Date으로부터 몇초후인지에 대한 시간정보를 통해, 현재 시점의 UTC시간을 저장한다.
- 암시적인 시간 + 날짜로 구성
- now.timeIntervalSinceReferenceDate => 기준 시간으로부터 몇 초가 떨어져있는지
- 데이터를 제대로 사용하려면 Calendar, TimeZone으로 잘 변환해서 사용해야함.
- Reference Date로부터 몇초 후를 저장하기 때문에 now - 86400을 하면 어제의 UTC시간이 된다.
💥2. TimeInterval
let oneSecond = TimeInterval(1.0) //1초 간격을 의미
- 시간 간격을 의미
💥3. Calendar
gregorian(그레고리력): 양력(전세계표준달력)
var calendar = Calendar.current
Calendar(identifier: .gregorian)
//둘다 태양력을 의미을 의미
- Calendar.autoupdatingCurrent -> 유저가 선택한 달력 기준(세계적인 서비스를 한다면?)
3-1. Calendar.locale
국가/지역마다 달력의 표기법이 다르기때문에 이를 설정한다.
예) 한국: 년/월/일, 미국: 월/일/년
한국의 locale설정
calendar.locale = Locale(identifier: "ko_KR")
3-2. Calendar.timeZone
서울의 시간은 영국의 시간보다 빠르기 때문에 timeZone설정이 필요하다.
한국의 timeZone설정
calendar.timeZone = TimeZone(identifier: "Asia/Seoul")
💥Calendar를 활용한 년/월/일/시/분/초 뽑아내기
let now = Date()
// (원하는)요소로 요소화 시키는 메서드(타입 알려주면 그것을 정수로 반환)
//:> Date의 "년/월/일/시/분/초"를 확인하는 방법
// 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)
// 실제 앱에서 표시할때는 위와 같은 식으로 분리해서, 레이블(Label)에 표시 가능
// 3) 요일
let weekday: Int = calendar.component(.weekday, from: now)
4. DateFormatter
시간을 원하는 타입으로 만들어주는 Formatter
let dateStr = "2020-08-13 16:30" // Date 형태의 String
let nowDate = Date() // 현재의 Date (ex: 2020-08-13 09:14:48 +0000)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm" // 2020-08-13 16:30
let convertDate = dateFormatter.date(from: dateStr) // Date 타입으로 변환
let myDateFormatter = DateFormatter()
myDateFormatter.dateFormat = "yyyy.MM.dd a hh시 mm분" // 2020.08.13 오후 04시 30분
myDateFormatter.locale = Locale(identifier:"ko_KR") // PM, AM을 언어에 맞게 setting (ex: PM -> 오후)
let convertStr = myDateFormatter.string(from: convertDate!)
let convertNowStr = myDateFormatter.string(from: nowDate) // 현재 시간의 Date를 format에 맞춰 string으로 반환
앨런님의 자료를 보고 공부했습니다.