我试着比较两天忽略时间。所以我用
calendar.compare(date1, to: date2, toGranularity: .day)
但是当将字符串日期传输到Date类型时,它将转换为UTC。所以它将从2016年1月1日0:05“移动”到2015年12月31日晚上11:05。每日比较时,这仅包括剩余的小时。在转换之前它是24小时。有什么想法不费吹灰之力地处理这个问题?
此外: 代码:
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy hh:mm"
var date1 : Date = dateFormatter.date(from: "01-01-2016 00:05")!
var date2 = dateFormatter.date(from: "01-01-2016 03:30")
if let dateFromString = dateFormatter.date(from: "01-01-2016 00:05") {
print(dateFromString)
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
let stringFromDate = dateFormatter.string(from: dateFromString)
}
Calendar.current.compare(date1, to: date2!, toGranularity: .day) == .orderedSame
答案 0 :(得分:12)
基于使用dateComponents(_:from:to:)函数
import Foundation
extension Date {
func totalDistance(from date: Date, resultIn component: Calendar.Component) -> Int? {
return Calendar.current.dateComponents([component], from: self, to: date).value(for: component)
}
func compare(with date: Date, only component: Calendar.Component) -> Int {
let days1 = Calendar.current.component(component, from: self)
let days2 = Calendar.current.component(component, from: date)
return days1 - days2
}
func hasSame(_ component: Calendar.Component, as date: Date) -> Bool {
return self.compare(with: date, only: component) == 0
}
}
不要忘记在此处输入解决方案代码(上图)
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy hh:mm:ss"
//dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
let smallerDate = dateFormatter.date(from: "01-01-2012 00:05:01")!
let biggerDate = dateFormatter.date(from: "03-12-2019 09:30:01")!
print(smallerDate.totalDistance(from: biggerDate, resultIn: .day)) // Optional(2893)
print(biggerDate.totalDistance(from: smallerDate, resultIn: .day)) // Optional(-2893)
print(smallerDate.totalDistance(from: biggerDate, resultIn: .year)) // Optional(7)
print(biggerDate.totalDistance(from: smallerDate, resultIn: .year)) // Optional(7)
print(smallerDate.totalDistance(from: biggerDate, resultIn: .hour)) // Optional(69441)
print(biggerDate.totalDistance(from: smallerDate, resultIn: .hour)) // Optional(-69441)
print(smallerDate.compare(with: biggerDate, only: .day)) // -2
print(biggerDate.compare(with: smallerDate, only: .day)) // 2
print(smallerDate.compare(with: biggerDate, only: .year)) // -7
print(biggerDate.compare(with: smallerDate, only: .year)) // 7
print(smallerDate.compare(with: biggerDate, only: .hour)) // -9
print(biggerDate.compare(with: smallerDate, only: .hour)) // 9
print(smallerDate.hasSame(.day, as: biggerDate)) // false
print(biggerDate.hasSame(.second, as: smallerDate)) // true