gpt4 book ai didi

swift3 - 如何在 swift 3.0 中比较日期?

转载 作者:行者123 更新时间:2023-12-04 09:58:11 26 4
gpt4 key购买 nike

我有两个日期,我想比较一下。
如何比较日期?
我必须约会对象。说modificateionDate较旧的 updatedDate .

那么比较日期的最佳做法是什么?

最佳答案

根据@NiravD 的回答,DateComparable .但是,如果要与给定粒度进行比较,可以使用 Calendarcompare(_:to:toGranularity:)
例子…

let dateRangeStart = Date()
let dateRangeEnd = Date().addingTimeInterval(1234)

// Using granularity of .minute
let order = Calendar.current.compare(dateRangeStart, to: dateRangeEnd, toGranularity: .minute)

switch order {
case .orderedAscending:
print("\(dateRangeEnd) is after \(dateRangeStart)")
case .orderedDescending:
print("\(dateRangeEnd) is before \(dateRangeStart)")
default:
print("\(dateRangeEnd) is the same as \(dateRangeStart)")
}

> 2017-02-17 10:35:48 +0000 is after 2017-02-17 10:15:14 +0000

// Using granularity .hour
let order = Calendar.current.compare(dateRangeStart, to: dateRangeEnd, toGranularity: .hour)

> 2017-02-17 10:37:23 +0000 is the same as 2017-02-17 10:16:49 +0000

关于swift3 - 如何在 swift 3.0 中比较日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42294529/

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