오늘은 날짜를 다루는법에 대해서 공부했다.
먼저 Swift에서 날짜를 다루는 타입으로는 Date,calendar,DateFormatter,component,TimeInterval 등 여러가지가 있다.
1. 현재 날짜 출력하기
let now = Date() // "Oct 29, 2020 at 10:27 PM"
Date()를 사용해서 현재 날짜와 시간을 확인할 수 있다.
2. "ko_kr"로 표기하기 (문자열로 바꾸기)
// 현재 날짜
var now = Date()
let df = DateFormatter()
df.locale = Locale(identifier: "ko_kr")
df.dateStyle = .full
df.timeStyle = .medium
df.string(from: now) // "2020년 10월 29일 목요일 오후 10:34:24"
한글로 날짜와 시간을 표시하고 싶다면 locale 설정을 바꿔주어야 한다.
DateFormatter를 이용해서 locale을 Ko_kr => 한국 으로 변경해주면"2020년 10월 29일 목요일 오후 10:34:24"로 출력된다.
3. 년 / 월 / 일 / 시 / 분 / 초 출력하기
df.string(from: now) // 2020년 10월 29일 목요일 오후 10:40:46
var calendar = Calendar.current
calendar.component(.second, from: now) // 46
calendar.component(.minute, from: now) // 40
calendar.component(.hour, from: now) // 10
calendar.component(.day, from: now) // 29
calendar.component(.month, from: now) // 10
calendar.component(.year, from: now) // 2020
현재 시간에서 내가 원하는 요소만 출력하고 싶을경우에는 component 메소드를 사용하면 요소(년, 월, 일, 요일, 시, 분) 등등 원하는 요소를 정수로 얻을 수 있다.
4. 날짜 계산해보기
var minute = TimeInterval(60 * 1)
var hour = TimeInterval(minute * 60)
var day = TimeInterval(hour * 24)
// 한달 30일로 고정해서 사용
var month = TimeInterval(60 * 1 * 60 * 24 * 30)
var year = TimeInterval(60 * 1 * 60 * 24 * 365)
let today = Date() // "Oct 29, 2020 at 10:56 PM"
let result = Date(timeIntervalSinceNow: year * -1) // "Oct 30, 2019 at 10:56 PM"
df.string(from: today) // "2020년 10월 29일 목요일 오후 10:56:24"
df.string(from: result) // "2019년 10월 30일 수요일 오후 10:56:24"
TimeInterval의 값은 항상 초 단위로 지정된다. 직접 년, 월, 일, 시, 분, 초를 구할수있는데 월부터는 28일, 30일, 31일로 끝나는 달이 다 달라 정확하게 기준을 잡고 계산해야한다.
timeIntervalSinceNow 메소드로 현재 시간에서 먼저 계산해놓은 요소들로 더하거나 뺄 수 있다.
5. 날짜와 시간 구분해서 출력하기
// 년 월 일 요일 출력
let today = Date()
let df = DateFormatter()
df.locale = Locale.init(identifier: "ko_kr")
df.dateStyle = .full
df.timeStyle = .none
df.string(from: today) // "2020년 10월 29일 목요일"
// 시간 출력
let today = Date()
let df = DateFormatter()
df.locale = Locale.init(identifier: "ko_kr")
df.dateStyle = .none
df.timeStyle = .medium
df.string(from: today) // "오후 11:04:26"
.dateStyle만 속성을 부여해주면 날짜만 출력된다.
.timeStyle만 속성을 부여해주면 시간만 출력된다.
'Swift > 기타' 카테고리의 다른 글
| Swift - 꼬리 재귀 함수 (0) | 2023.07.07 |
|---|---|
| 재귀함수 (0) | 2023.06.27 |
| CoreData (1) (0) | 2023.05.28 |