ios) Date

2 minute read

Date

Cocoa Tuch Framework에는 날짜를 처리하는 다양한 자료형이 선언되어있다.

Class Structure
NSDate Date
NSCalendar Calendar
NSDateComponents DateComponents
NSTimeZone TimeZone
NSLocale Locale

예전에는 Class로 구현된 자료형만 제공했지만 요즘은 구조체로 구현된 자료형도 제공한다.

let time = Date()

이렇게 코드를 실행하면 현재 날짜와 시간이 표시되는 인스턴스가 생성된다.

공식문서의 Date 생성 부분을 참고하게 되면 Date 클래스를 생성함으로서 우리가 구할 수 있는 다음과 같다.

스크린샷 2021-01-10 오후 8 10 46

init()
// 현재 시점의 날짜와 시간(시스템에 찍힌)
init(timeIntervalSinceNow: TimeInterval)
//현재 날짜를 기준으로 매개변수로 전달된 TimeInterval만큼 후의 시간(-값을 전달할 경우 전의 시간)
init(timeInterval: TimeInterval, since: Date)
//since 매개변수로 전달된 시점의 시간에 TimeInterval만큼 후의 시간(-값을 전달할 경우 전의 시간)
init(timeIntervalSinceReferenceDate: TimeInterval)
//21세기 시작 지점 2001. 1. 1 00:00:00 UTC를 기준으로 TimeInterval만큼 후의 시간
init(timeIntervalSince1970: TimeInterval)
// epoch(Unix 기준 시작 시점) 1970. 1. 1 00:00:00 UTC를 기준으로 Time Interval만큼 후의 시간

TimeInterval

스크린샷 2021-01-10 오후 8 25 46

날짜와 시간은 TimeInterval 단위로 처리한다.

TimeInterval은 초단위의 값을 저장한다. -> 1.0(Time Interval) == 1.0(Second)

하루(86400초)를 이용한 특정 시간을 구현해 보도록 하자.

let now = Date()
// Jan 10, 2021 at 8:43 PM
let tomorrowFromNow = Date(timeIntervalSinceNow: 86400)
// Jan 11, 2021 at 8:43 PM
let yesterdayFromNow = Date(timeIntervalSinceNow: -86400)
// Jan 9, 2021 at 8:43 PM
let theDayAfterTomorrow = Date(timeInterval: 86400, since: tomorrowFromNow)
// Jan 12, 2021 at 8:43 PM
let timeSince2001 = Date(timeIntervalSinceReferenceDate: 86400)
// Jan 2, 2001 at 9:00 AM
let timeSince1970 = Date(timeIntervalSince1970: 86400)
// Jan 2, 1970 at 9:00 AM

TimeIntervel은 연산자도 사용할 수 있다.

다만, 연산자에 입력되는 파라미터는 항상 Date, TimeInterval(초) 혹은 Date, Date이어야 한다.


Calendar

Date에 저장된 값은 특정 달력과 연관되지 않은 독립적인 값이다.

우리가 주로 사용하는 날짜와 시간은 양력이다.

그래서 날짜와 시간을 표시하거나 계산을 수행하려면 특정 달력인스턴스의 도움을 받아야한다.

캘린더는 Calendar.Identifier열거형에 구현되어있는 맴버를 통해 생성할 수 있다.

하지만 캘린더는 Current 속성이나 autoupdatingCurrent 속성이 리턴하는 캘린더를 그대로 사용한다.

let calendar = Calendar.autoupdatingCurrent
// 아이폰 설정에서 선택되어 있는 달력을 리턴

별다른 이유가 없다면 사용자가 설정해둔 달력과 동일한 달력을 사용하는 것이 좋다.


DateComponents

날짜는 year, month, day로 구성되어있고

시간은 hour, minute, second로 구성되어있다.

이러한 값들은 DateComponents 형식으로 처리한다.

밑에 코드는 날짜를 생성하는 코드이다.

let calendar = Calendar.autoupdatingCurrent
var components = DateComponents()
components.year = 2019
components.month = 10
components.day = 28

let date = calendar.date(from: components)//Oct 28, 2019 at 12:00 AM

현저 설정된 캘린더를 가지고 온 후, 새로운 dateComponents인스턴스를 생성한다.

그리고 인스턴스 속성에 원하는 날짜와 시간을 설정한다.

캘린더에 구현되어있는 date(from:)메서드를 통해 DateComponents로 설정된 날짜를 생성한다.

component(from:)메서드를 통해 하나의 component만 확인도 가능하다.

날짜를 계산할 때에도 calendar와 dateComponets가 필요하다.

let startDate = calendar.date(from: components)

let days = calendar.dateComponents([.day], frome: startDate!, to: now).day

dateComponents(from:to:)메서드에 단위와 날짜를 전달하고,

리턴 된 인스턴스에서 day 속성에 저장된 값을 읽는 코드이다.


TimeZone

Date에 저장된 날짜는 UTC TimeZone 값으로 저장되어 있다.

UTC는 Coordinated Universal Time의 약자로

협정 세계시를 말한다. 기준일자는 Reference Date이며 2020.01.01 00:00:00 이고

여기에 숫자를 더하면 이후날짜 숫자를 빼면 이전 날짜를 구할 수 있다.

//Reference Date로부터 한시간 이 후 날짜
Date(timeIntervalSinceReferenceDate: 60 * 60)
//Reference Date로부터 한시간 이 전 날짜
Date(timeIntervalSinceReferenceDate: -60 * 60)

한국의 TimeZone이름은

Korean Standard Time이고, 줄여서 KST이다. UTC+09:00 UTC와의 9시간의 시차가 있다.

Cocoa Tuch Framework에서 사용가능한 TimeZone은

for name in TimeZone.knownTimeZoneIdentifiers {
  print(name)
} // Asia / Seoul

이 코드를 통해 확인 할 수 있다.

TimeZone을 별도로 설정하지 않으면 아이폰의 기본설정을 그대로 사용한다.

직접 지정 할 때에는 DateComponents에 TimeZone속성을 사용한다.

let calendar = Calendar.current
var components = DateComponents()
components.year = 2014
components.month = 4
components.day = 16
components.timeZone = TimeZone(identifier: "America/Los_Angeles")

let date = calendar.date(from: components)

TimeZone을 직접 사용할 때에는 이러한 코드를 사용한다.

Comments