SwiftUIの基本を身につけたい方はこちら

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

UnixTimeを取得する方法

let date = Date()
let unixtime = date.timeIntervalSince1970
print(unixtime)

現在日時を取得する方法

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

時間を追加する方法

現在時刻に1時間追加する

let date = Date()
let modifiedHour = Calendar.current.date(byAdding: .hour, value: 1, to: date)!
print(modifiedHour.description)

日付の比較

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)

評価