gpt4 book ai didi

swift - 如何计算 Swift 中两个日期的天数差异,因为天数从早上 6 点开始而不是 0

转载 作者:搜寻专家 更新时间:2023-11-01 05:34:23 24 4
gpt4 key购买 nike

我试图找出两个 Date 对象的不同之处。我基本上知道怎么做,就像这样:

        let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale.current

print(count)
// print(history[count - 1].value(forKey: "multipleURLs") as! [String])
let latestDate = history[count - 1].value(forKey: "date") as! Date
let calendar = Calendar.current

let components = calendar.dateComponents([.year, .month, .day, .hour], from: date)

let nowDate = calendar.startOfDay(for: date)
let lastDate = calendar.startOfDay(for: latestDate)

let diffDateComponent = (calendar as NSCalendar).components([NSCalendar.Unit.year, NSCalendar.Unit.month, NSCalendar.Unit.day], from: lastDate, to: nowDate, options: NSCalendar.Options.init(rawValue: 0))

print("Status Checked" + String(describing: diffDateComponent.day))

但我试图将结果作为一天从早上 6 点开始而不是 0 点开始。

所以我做了这样的事情:

        let nowDate = calendar.startOfDay(for: date.addingTimeInterval(-3600))
let lastDate = calendar.startOfDay(for: latestDate.addingTimeInterval(-3600))

但它似乎不起作用,谁能帮我解决这个问题?

最佳答案

这会将每个日期设置为早上 6 点(在 Date 的当前语言环境中):

import Foundation

// set up dates
let calendar = Calendar.current
let date = Date()
if let latestDate = calendar.date(byAdding: .day, value: -5, to: date) {

// set each day to 6 AM
if let nowDate = calendar.date(bySettingHour: 6, minute: 0, second: 0, of: date ),
let lastDate = calendar.date(bySettingHour: 6, minute: 0, second: 0, of: latestDate) {

print( date.description(with: .current),
nowDate.description(with: .current),
lastDate.description(with: .current),
separator: "\n")

// calculate difference in days
if let days = calendar.dateComponents([.day], from: lastDate, to: nowDate).day {
print("Days since: \(days)")
}
}
}

// Thursday, June 8, 2017 at 7:59:42 AM Eastern Daylight Time
// Thursday, June 8, 2017 at 6:00:00 AM Eastern Daylight Time
// Saturday, June 3, 2017 at 6:00:00 AM Eastern Daylight Time
// Days since: 5

关于swift - 如何计算 Swift 中两个日期的天数差异,因为天数从早上 6 点开始而不是 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44434465/

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