gpt4 book ai didi

swift - 在以下示例中如何计算日差

转载 作者:行者123 更新时间:2023-11-28 12:47:03 24 4
gpt4 key购买 nike

我正在计算两个日期之间的天数差异,但我发现以下代码实际上是给我 24 小时的差异而不是日期差异。我有以下代码:

func daysBetweenDate(startDate: NSDate, endDate: NSDate) -> Int
{
let calendar = NSCalendar.currentCalendar()

let components = calendar.components([.Day], fromDate:startDate, toDate: endDate, options: [])

return components.day
}

因此,对于以下示例,我得到了这个结果:

lastLaunch:2016-06-10 01:39:07 +0000

今天:2016-06-11 00:41:41 +0000

日差:0

我原以为会有一天的差异,因为上次发布是在 10 日,而今天是 11 日。如何更改代码以提供几天的实际日期差异?

最佳答案

您可以使用日历方法 date BySettingHour 获取开始日期和结束日期的中午时间,以使您的日历计算对时间不敏感:

Xcode 8.2.1 • Swift 3.0.2

extension Date {
var noon: Date? {
return Calendar.autoupdatingCurrent.date(bySettingHour: 12, minute: 0, second: 0, of: self)
}
func daysBetween(_ date: Date) -> Int? {
guard let noon = noon, let date = date.noon else { return nil }
return Calendar.autoupdatingCurrent.dateComponents([.day], from: noon, to: date).day
}
}

let startDateString = "2016-06-10 01:39:07 +0000"
let todayString = "2016-06-11 00:41:41 +0000"
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "ex_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss xxxx"
if let startDate = formatter.date(from: startDateString),
let endDate = formatter.date(from: todayString),
let days = startDate.daysBetween(endDate) {
print(startDate) // "2016-06-10 01:39:07 +0000\n"
print(endDate) // "2016-06-11 00:41:41 +0000\n"
print(days ?? "nil") // 1
}

swift 2.x

extension NSDate {
var noon: NSDate {
return NSCalendar.currentCalendar().dateBySettingHour(12, minute: 0, second: 0, ofDate: self, options: [])!
}
}
func daysBetweenDate(startDate: NSDate, endDate: NSDate) -> Int {
return NSCalendar.currentCalendar().components([.Day],
fromDate: startDate.noon,
toDate: endDate.noon,
options: []).day
}

关于swift - 在以下示例中如何计算日差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37759037/

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