[英]Swift: Compare date by days
我嘗試比較兩天而忽略時間。 所以我用
calendar.compare(date1, to: date2, toGranularity: .day)
但是當將字符串日期轉換為 Date 類型時,它會轉換為 UTC。 所以它將從 1.1.2016 0:05 到 31.12.2015 11:05 pm“移動”。 在按日比較時,這僅包括剩余的小時。 在轉換之前是 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
基於使用dateComponents(_:from:to:)函數
import Foundation
extension Date {
func fullDistance(from date: Date, resultIn component: Calendar.Component, calendar: Calendar = .current) -> Int? {
calendar.dateComponents([component], from: self, to: date).value(for: component)
}
func distance(from date: Date, only component: Calendar.Component, calendar: Calendar = .current) -> Int {
let days1 = calendar.component(component, from: self)
let days2 = calendar.component(component, from: date)
return days1 - days2
}
func hasSame(_ component: Calendar.Component, as date: Date) -> Bool {
distance(from: 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.fullDistance(from: biggerDate, resultIn: .day)) // Optional(2893)
print(biggerDate.fullDistance(from: smallerDate, resultIn: .day)) // Optional(-2893)
print(smallerDate.fullDistance(from: biggerDate, resultIn: .year)) // Optional(7)
print(biggerDate.fullDistance(from: smallerDate, resultIn: .year)) // Optional(7)
print(smallerDate.fullDistance(from: biggerDate, resultIn: .hour)) // Optional(69441)
print(biggerDate.fullDistance(from: smallerDate, resultIn: .hour)) // Optional(-69441)
print(smallerDate.distance(from: biggerDate, only: .day)) // -2
print(biggerDate.distance(from: smallerDate, only: .day)) // 2
print(smallerDate.distance(from: biggerDate, only: .year)) // -7
print(biggerDate.distance(from: smallerDate, only: .year)) // 7
print(smallerDate.distance(from: biggerDate, only: .hour)) // -9
print(biggerDate.distance(from: smallerDate, only: .hour)) // 9
print(smallerDate.hasSame(.day, as: biggerDate)) // false
print(biggerDate.hasSame(.second, as: smallerDate)) // true
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.