[iOS/Swift] 날짜와 시간 다루기

최정은·2023년 9월 12일
0

Swift

목록 보기
22/27

UTC

  • 국제적인 표준 시간

Date

  • 절대적 시점(초 기준)
  • 객체를 생성할 때, 기준 시간을 기점으로 몇 초 후 인지에 대한 시간 정보를 통해, 현재 시점을 저장

(1) UTC 기준

  • 2001.1.1. 00:00:00 UTC

(2) 유닉스 기준

  • 1970.1.1. 00:00:00 UTC

Calendar

  • 달력 및 달력의 요소를 다루는 Calendar 구조체 (양력/음력 ...인지)
  • 년/월/일 + 시/분/초 + 요일

DateFormatter

  • "형식" 문자열로 변형해 주는 DateFormatter 클래스
  • 표시하기 위한 문자열

날짜와 시간을 다루는 Date 구조체의 인스턴스

let now = Date()
print(now) // UTC 기준 시간 > yyyy-MM-dd HH:mm:ss +0000

1초 간격

let oneSecond = TimeInterval(1.0)

Calendar 구조체의 이해

생성

var calendar = Calendar.current

지역설정

calendar.locale // 달력의 지역 (영어/한국어)
calendar.timeZone // 타임존 => Asia/Seoul

calendar.locale = Locale(identifier: "ko_KR")

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)

// 3) 요일
let weekday: Int = calendar.component(.weekday, from: now)
// 일요일 - 1
// 월요일 - 2
// 화요일 - 3
// ...
// 토요일 - 7

Date 한 번에 확인

let myCal = Calendar.current
var myDateCom = myCal.dateComponents([.year, .month, .day], from: now)

print("\(myDateCom.year!)\(myDateCom.month!)\(myDateCom.day!)일")

DateFormatter

날짜와 시간을 원하는 형식의 문자열(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)

문자열에서 Date 로 변환

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)! 

구조체 확장 활용

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)

0개의 댓글