Date Formatter를 활용해서 날짜를 문자열로, 문자열을 날짜로 바꾸는 방법
let now = Date()
print(now)
날짜를 원하는 형식으로 바꿀때는 DateFormatter를 사용합니다.
let formatter = DateFormatter()
formatter.dateStyle = .full // 날짜 형식
formatter.timeStyle = .medium // 시간 형식
formatter.locale = Locale(identifier: "ko_KR")
var result = formatter.string(from: now)
print(result)
// 파라미터로 전달하는 날짜가 옵셔널이라면 string(for:) 사용
formatter.string(for: now)
DateFormatter.localizedString(from: now, dateStyle: .long, timeStyle: .short)
let now = Date()
let formatter = DateFormatter()
// 포맷 문자열을 통해서 지역화된 문자열을 얻을때 사용
formatter.locale = Locale(identifier: "en_US")
formatter.setLocalizedDateFormatFromTemplate("yyyyMMMMdE")
var result = formatter.string(from: now)
print(result)
print(formatter.dateFormat)
formatter.locale = Locale(identifier: "ko_KR")
formatter.setLocalizedDateFormatFromTemplate("yyyyMMMMdE")
result = formatter.string(from: now)
print(result)
print(formatter.dateFormat)
let now = Date()
let yesterday = now.addingTimeInterval(3600 * -24)
let tomorrow = now.addingTimeInterval(3600 * 24)
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "ko_KR")
formatter.dateStyle = .full
formatter.timeStyle = .none
formatter.doesRelativeDateFormatting = true // 이걸 사용하면 오늘, 어제, 내일, 그저께, 모레 등으로 바꿀수 있다.
print(formatter.string(from: now))
print(formatter.string(from: yesterday))
print(formatter.string(from: tomorrow))
let now = Date()
let weekdaySymbols = ["☀️", "🌕", "🔥", "💧", "🌲", "🥇", "🌏"]
let am = "🌅"
let pm = "🌇"
let formatter = DateFormatter()
formatter.dateStyle = .full
formatter.timeStyle = .full
print(formatter.string(from: now))
formatter.amSymbol = am
formatter.pmSymbol = pm
formatter.weekdaySymbols = weekdaySymbols
print(formatter.string(from: now))
let str = "2017-09-02T09:30:00Z"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
if let date = formatter.date(from: str) {
formatter.dateStyle = .full
formatter.timeStyle = .full
print(formatter.string(from: date))
} else {
print("invalid format")
}