【Xcode/Swift】Date()チートシート

現在日時を取得する方法

let dt = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = DateFormatter.dateFormat(fromTemplate: "yMMMdHms", options: 0, locale: Locale(identifier: "ja_JP"))
print(dateFormatter.string(from: dt))

日付の比較

let startDate = "2020-7-24"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let formatedStartDate = dateFormatter.date(from: startDate)
let currentDate = Date()

let elapsedDays = Calendar.current.dateComponents([.day], from: currentDate, to: formatedStartDate!).day!

print(elapsedDays)