Swift 斯威夫特为什么不是';t我的日期对象为';将其转换为字符串并返回后,s(equalable)是否相等?

Swift 斯威夫特为什么不是';t我的日期对象为';将其转换为字符串并返回后,s(equalable)是否相等?,swift,date,Swift,Date,我正在编写一个单元测试来检查从日期到字符串再到日期的转换是否成功 我通过以下方式将其转换为字符串: func convertDateToString(date: Date) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" return dateFormatter.string(from: date) } 并通过以下方式将

我正在编写一个单元测试来检查从日期到字符串再到日期的转换是否成功

我通过以下方式将其转换为字符串:

func convertDateToString(date: Date) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    return dateFormatter.string(from: date)
}
并通过以下方式将其转换回:

func convertStringToDate(string: String) -> Date {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    return dateFormatter.date(from: string)!
}
如果您尝试在转换前日期和转换后日期使用Equatable协议,则表示它们不相同。但是,如果将日期前后转换为字符串并进行比较,则它们是相等的。这是我在日期前和日期后运行XcassertQual时所说的:

XCTAssertEqual failed: ("2020-01-22 19:35:40 +0000") is not equal to ("2020-01-22 19:35:40 +0000")

我觉得很像。我甚至尝试将转换前的日期转换为字符串并返回,以检查日期是否相等,但它们仍然不相等。

问题在于,
日期
存储为
浮点值(timeintervalncereferencedate)。将
日期
转换为
字符串
并返回到
日期
时,会丢弃小数秒。看看。

存在的问题是,
日期
存储为
浮动点
值(timeintervalncereferencedate)。将
日期
转换为
字符串
并返回到
日期
时,会丢弃小数秒。看一看。

它肯定是
可平衡的
,只是不相等。@Alexander说得很好。它肯定是
可平衡的
,只是不相等。@Alexander说得很好。