使用Swift 3,可以根据需要选择以下两种模式之一来解决问题。
#1 使用compare(_:to:toGranularity:)
方法
Calendar
有一种称为的方法compare(_:to:toGranularity:)
。compare(_:to:toGranularity:)
具有以下声明:
func compare(_ date1: Date, to date2: Date, toGranularity component: Calendar.Component) -> ComparisonResult
将给定日期与给定组件进行比较,orderedSame
如果给定组件和所有较大组件中的日期相同,则报告这些日期,否则为orderedAscending
或orderedDescending
。
下面的Playground代码显示了使用它的热点:
import Foundation
let calendar = Calendar.current
let date1 = Date()
let date2 = calendar.date(byAdding: .day, value: -1, to: date1)!
let date3 = calendar.date(byAdding: .hour, value: 1, to: date1)!
do {
let comparisonResult = calendar.compare(date1, to: date2, toGranularity: .day)
switch comparisonResult {
case ComparisonResult.orderedSame:
print("Same day")
default:
print("Not the same day")
}
}
do {
let comparisonResult = calendar.compare(date1, to: date3, toGranularity: .day)
if case ComparisonResult.orderedSame = comparisonResult {
print("Same day")
} else {
print("Not the same day")
}
}
#2。使用dateComponents(_:from:to:)
Calendar
有一种称为的方法dateComponents(_:from:to:)
。dateComponents(_:from:to:)
具有以下声明:
func dateComponents(_ components: Set<Calendar.Component>, from start: Date, to end: Date) -> DateComponents
返回两个日期之间的差。
下面的Playground代码显示了使用它的热点:
import Foundation
let calendar = Calendar.current
let date1 = Date()
let date2 = calendar.date(byAdding: .day, value: -1, to: date1)!
let date3 = calendar.date(byAdding: .hour, value: 1, to: date1)!
do {
let dateComponents = calendar.dateComponents([.day], from: date1, to: date2)
switch dateComponents.day {
case let value? where value < 0:
print("date2 is before date1")
case let value? where value > 0:
print("date2 is after date1")
case let value? where value == 0:
print("date2 equals date1")
default:
print("Could not compare dates")
}
}
do {
let dateComponents = calendar.dateComponents([.day], from: date1, to: date3)
switch dateComponents.day {
case let value? where value < 0:
print("date2 is before date1")
case let value? where value > 0:
print("date2 is after date1")
case let value? where value == 0:
print("date2 equals date1")
default:
print("Could not compare dates")
}
}