본문 바로가기
iOS

[iOS] DateFormatter vs Formatted

by seongminmon 2024. 9. 26.

1. DateFormatter

DateFormatter를 이용해 Date의 format을 설정할 수 있음

표기 - yyyy(년) MM(월) dd(일) hh(시간) mm(분) ss(초) a(오전/오후) EEEE(요일)

let date = Date()
print(date)

let formatter = DateFormatter()
formatter.dateFormat = "yyyy년 MM월 dd일"
print(formatter.string(from: date))
formatter.dateFormat = "yy년 M월 d일"
print(formatter.string(from: date))
2024-05-26 14:31:26 +0000
2024년 05월 26일
24년 5월 26일

 

2. Formatted

iOS15부터 등장
숫자, 날짜, 시간 등과 같은 데이터를 사용자가 사용하는 현지화된 문자열로 변환해 줌
사용자 디바이스의 위치와 언어 설정에 따라 결과는 다르게 나올 수 있음

let date = Date()
print(date)

print(date.formatted())
print(date.formatted(date: .omitted, time: .shortened))
print(date.formatted(date: .complete, time: .shortened))

let locale = Locale(identifier: "ko-KR")
print(date.formatted(.dateTime.locale(locale).day().month(.twoDigits).year()))
print(date.formatted(.dateTime.day().month(.twoDigits).year()))
2024-05-26 14:27:03 +0000
5/26/2024, 11:27 PM
11:27 PM
Sunday, May 26, 2024 at 11:27 PM
2024. 05. 26.
05/26/2024