请解释一下,为什么我的代码无法按预期工作。我正在尝试比较两个日期,但结果是错误的。
在Swift 5.0中进行了测试。
import UIKit
func getDateFromString(_ dateStr: String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.zzz"
return dateFormatter.date(from: dateStr)
}
let date1 = "2019-05-13T08:25:26.000"
let date2 = "2019-05-13T08:25:26.500"
let date3 = "2019-05-13T08:25:27.000"
let date1Obj = getDateFromString(date1)!
let date2Obj = getDateFromString(date2)!
let date3Obj = getDateFromString(date3)!
date1Obj < date2Obj // FALSE, why ?
date2Obj < date3Obj // TRUE, worked as expected, because dates have different seconds
date1Obj < date3Obj // TRUE, worked as expected
// Same result if i compare timeIntervalSinceReferenceDate
date1Obj.timeIntervalSinceReferenceDate < date2Obj.timeIntervalSinceReferenceDate // FALSE, why ?
date2Obj.timeIntervalSinceReferenceDate < date3Obj.timeIntervalSinceReferenceDate // TRUE, worked as expected
date1Obj.timeIntervalSinceReferenceDate < date3Obj.timeIntervalSinceReferenceDate // TRUE, worked as expected
// I thought that Date does not store a millisecond, but when i looked timeIntervalSinceReferenceDate
date1Obj.timeIntervalSinceReferenceDate // 579428726
date2Obj.timeIntervalSinceReferenceDate // 579428725.5 // I think this is not correct value.
date3Obj.timeIntervalSinceReferenceDate // 579428727