gpt4 book ai didi

ios - Swift 4 中更新数据库的两个日期的比较

转载 作者:行者123 更新时间:2023-11-28 14:38:23 26 4
gpt4 key购买 nike

我有这个代码:

func getSystemDate()-> String{
let date = Date()
let calendar = Calendar.current
let hour = String(format: "%02d",calendar.component(.hour, from: date))
let minutes = String(format: "%02d",calendar.component(.minute, from: date))
let seconds = String(format: "%02d",calendar.component(.second, from: date))

let day = String(format: "%02d",calendar.component(.day, from: date))
let month = String(format: "%02d",calendar.component(.month, from: date))
let year = String(format: "%02d",calendar.component(.year, from: date))

let fullDate = "\(year)-\(month)-\(day) \(hour):\(minutes):\(seconds)"

return fullDate
}
let date1 = getSystemDate()
let date2 = "2018-05-23 13:14:47"

if date1 > date2 {
print("its ok - update available")
} else {
print("wrong - you have actually database")
}

我的函数 getSystemDate() 返回字符串中的实际日期。在变量 date2 中 - 我有数据库更新日期。

我需要确定是否可以更新数据库并将当前日期与可用数据库的日期进行比较:...

如何比较这些日期?

最佳答案

您可以使用 Calendar 来比较两个 Date。您也可以转到 second unit,如果差异为 0 则表示它们相等,否则您可以检查哪个更大:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
//dateFormatter.timeZone = TimeZone(abbreviation: "UTC") // To add timezone

guard let dateOne = dateFormatter.date(from: "2018-05-23 13:14:47"), let dateTwo = dateFormatter.date(from: "2018-05-23 14:14:47") else {
print("One of the date conversion is nil")
return
}

print(dateOne, dateTwo)

let components = Calendar.current.dateComponents([.second], from: dateOne, to: dateTwo)
let secondsInBetween: Int = components.second!

print(secondsInBetween)

关于ios - Swift 4 中更新数据库的两个日期的比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50716942/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com