IOS application/Swift

26. [Swift] 시간과 날짜: Date(), DateComponents()

개발자킹콩 2021. 8. 12. 10:17

개발을 진행하다 보면 날짜와 시간을 이용해야 하는 경우가 너무 많다.

그래서 날짜와 시간을 이용하는 Date와 DateComponents에 대해 살펴보자.

 

 


 

 

현재의 날짜와 시간 구하기

Swift 개발 문서에 따르면, Date는 어떠한 달력과 Time Zone과는 독립적인 특정 시점의 시간 포인트이다.

아래의 코드는 Date Class를 생성함으로 상대시간과 절대시간을 정할 수 있다.

 

// 득정 시점
init() // 현재 시점의 시스템의 날짜와 시간
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만큼 후의 시간

// 특정 시점으로부터 시간의 흐름
init(timeIntervalSinceNow: TimeInterval) //현재 날짜를 기준으로 TimeInterval만큼 후의 시간
init(timeInterval: TimeInterval, since: Date) // since 전달된 시점의 시간에 TimeInterval만큼 후의 시간

 

시간은 특정 시점을 기준으로 생각할 수 있고, 어떤 시점을 기준으로 흐름을 생각할 수도 있다.

아래의 예시를 살펴보면 바로 이해할 수 있을 것이다.

86400은 하루 24을 '초(s)'로 환산한 것이다.

 

import UIKit

let now = Date() //"2021-07-16 03:12:05 +0000"
let tomorrowFromNow = Date(timeIntervalSinceNow: 86400) //"2021-07-17 03:12:05 +0000"
let yesterdayFromNow = Date(timeIntervalSinceNow: -86400) //"2021-07-15 03:12:05 +0000"
let theDayAfterTomorrow = Date(timeInterval: 86400, since: tomorrowFromNow) //"2021-07-18 03:12:05 +0000"
let timeSince2001 = Date(timeIntervalSinceReferenceDate: 86400) //"2001-01-02 00:00:00 +0000"
let timeSince1970 = Date(timeIntervalSince1970: 86400) //"1970-01-02 00:00:00 +0000"

 

 

 


 

 

 

TimeInterval

timeInterval은 double형의 '초'라고 생각하면 된다. 간단하게 '초'를 파라미터로 전달하면 된다.

 

TimeInterval의 경우 +, -, >, <, >=, +=, 연산자를 활용할 수 있다.

 

입력되는 파라미터는 반드시 Date, TimeInterval(초) 이어야 한다.

 

import UIKit

let now = Date() // "2021-07-16 03:18:31 +0000"

let tomorrow = now + 86400 // "2021-07-17 03:18:31 +0000"
let yesterday = now - 86400 // "2021-07-15 03:18:31 +0000"

tomorrow > yesterday // true
now == tomorrow //false

 

 

 

 


 

 

 

DateFormatter 활용하기

date의 경우 어떤 시점을 기준으로 여러가지 연산을 진행할때 초단위를 이용하는 방법이다.

그렇다면 내가 원하는 임의의 날짜는 어떻게 만들 수 있을까?

 

dataFormat을 정확하게 명시한 후, 아래와 같이 date(from: String) 함수를 이용하여 date값으로 바꿀 수 있다.

 

import UIKit

let date = DateFormatter()
date.locale = Locale(identifier: "ko_kr")
date.dateFormat = "yyyy-MM-dd"

let time = date.date(from: "2021-07-16")
print(date) // <NSDateFormatter: 0x600000111cb0>
print(time) // Optional(2021-07-15 15:00:00 +0000)

 

 

 


 

 

 

date 값을 String으로 바꾸고자 하면 아래와 같이 진행하면 된다.

이때 dateFormate을 지정하는 것을 보면 이해하기 쉽다.

import UIKit

let now = Date()

let date = DateFormatter()
date.locale = Locale(identifier: "ko_kr")
date.timeZone = TimeZone(abbreviation: "KST")
date.dateFormat = "yyyy-MM-dd HH:mm:ss" 2021-07-16 14:20:17

let kr = date.string(from: now) // 2021-07-16 14:20:17

 

 

Locale identifier: https://gist.github.com/jacobbubu/1836273

 

iOS Locale Identifiers

iOS Locale Identifiers. GitHub Gist: instantly share code, notes, and snippets.

gist.github.com

Time Zone Abbreviation: https://en.wikipedia.org/wiki/List_of_time_zone_abbreviations

 

List of time zone abbreviations - Wikipedia

From Wikipedia, the free encyclopedia Jump to navigation Jump to search This is a list of time zone abbreviations. Time zones are often represented by alphabetic abbreviations such as "EST", "WST", and "CST", but these are not part of the international tim

en.wikipedia.org

 

 

 

 


 

 

 

 

몇시 몇분 몇초

 

각각의 일월시분초는 어떻게 구할수 있을까? 이때 사용하는 것이 calendar 구조체이다.

calendar structure는 달력에 잇는 단위 (년, 월, 일 등)를 계산하고 비교할 수 있다.

이때 사용되는 핵심 메소드는 dateComponents( _ : from ) 이다.

 

import UIKit

let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.hour, .minute, .second], from: date)

components.month //nil
components.hour //14
components.minute //27

 

dateComponents에 내가 원하는 시간, 날짜를 파라미터로 넘겨주면 optional int type으로 반환된다.

내가 원하지 않은 시간단위가 있기 때문이다.

 

참고로 현재 우리의 달력은 그레고리안 달력을 사용한다. default 값이다.

let calendat = Calendat(idnetifier: .gregorian)

 

 

 

 


 

 

 

날짜 사이 차이 구하기

 

날짜의 각각의 요소에도 접근해봤다. 그럼 날짜가 얼마나 차이나는지도 구할 수 있다.

 

 timeIntervalSince함수를 이용하여 interval을 구해 86400초(하루)로 나누어 구하는 방법

간단하게 날짜의 차이를 하루로 나누면 된다.

import UIKit

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let startDate = dateFormatter.date(from:"2018-03-01")!
let endDate = dateFormatter.date(from:"2018-05-15")!

let interval = endDate.timeIntervalSince(startDate)
let days = Int(interval / 86400)

print("\(days) 차이.")

 

 

아래 함수로 깔끔하게 구할 수도 있다.

 

import UIKit

let calendar = Calendar.current
let dateGap = calendar.dateComponents([.year,.month,.day,.hour], from: startDate, to: endDate)

if case let (y?, m?, d?, h?) = (dateGap.year, dateGap.month, dateGap.day, dateGap.hour) {
  print("\(y)년 \(m)개월 \(d)일 \(h)시간 후")
}

 

 

 

 


 

 

 

 

오늘을 기준으로 100일이 되는 날

 

DateComponents에 Int?를 넣어주며 day라는 DateComponents형 변수를 만든다.

calendar.date(byAdding: , to:) 함수를 활용하면 현재 날짜로부터 DataComponents의 요소만큼 더해준다.

 

import UIKit

let now = Date()
let calendar = Calendar.current
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"

let day = DateComponents(day: 99)
if let d100 = calendar.date(byAdding: day, to: now)
{
    print(dateFormatter.string(from: d100))
}

 

 

 

 


 

 

 

 

참고자료

 

DateFormatter.dateStyle 관련

DateFormatter() has 5 format style options for each of Date and Time. These are:
.none .short .medium .long .full

 DATE      TIME     DATE/TIME STRING
"none"    "none"    
"none"    "short"   9:42 AM
"none"    "medium"  9:42:27 AM
"none"    "long"    9:42:27 AM EDT
"none"    "full"    9:42:27 AM Eastern Daylight Time
"short"   "none"    10/10/17
"short"   "short"   10/10/17, 9:42 AM
"short"   "medium"  10/10/17, 9:42:27 AM
"short"   "long"    10/10/17, 9:42:27 AM EDT
"short"   "full"    10/10/17, 9:42:27 AM Eastern Daylight Time
"medium"  "none"    Oct 10, 2017
"medium"  "short"   Oct 10, 2017, 9:42 AM
"medium"  "medium"  Oct 10, 2017, 9:42:27 AM
"medium"  "long"    Oct 10, 2017, 9:42:27 AM EDT
"medium"  "full"    Oct 10, 2017, 9:42:27 AM Eastern Daylight Time
"long"    "none"    October 10, 2017
"long"    "short"   October 10, 2017 at 9:42 AM
"long"    "medium"  October 10, 2017 at 9:42:27 AM
"long"    "long"    October 10, 2017 at 9:42:27 AM EDT
"long"    "full"    October 10, 2017 at 9:42:27 AM Eastern Daylight Time
"full"    "none"    Tuesday, October 10, 2017
"full"    "short"   Tuesday, October 10, 2017 at 9:42 AM
"full"    "medium"  Tuesday, October 10, 2017 at 9:42:27 AM
"full"    "long"    Tuesday, October 10, 2017 at 9:42:27 AM EDT
"full"    "full"    Tuesday, October 10, 2017 at 9:42:27 AM Eastern Daylight Time

 

 


 

 

자료

https://macinjune.com/all-posts/web-developing/swift/xcode-swift-%EB%82%A0%EC%A7%9C%EC%99%80-%EC%8B%9C%EA%B0%84-%EB%8B%A4%EB%A3%A8%EA%B8%B0-date-datecomponents/

 

[Xcode / Swift] 날짜와 시간 다루기 | Date() DateComponents() - Mac In June

현재 시점의 날짜와 시간 구하기 Swift 개발 문서에 따르면, Date는 어떠한 달력과 Time Zone과는 독립적인 특정 시점의 시간 포인트이다. Date Class를 생성함으로 인해서 우리가 바로 구할 수 있는 값

macinjune.com