问题描述
我正在编写一个单元测试,以检查从日期到字符串并返回的转换是否成功。
I'm writing a unit test to check that my conversion from a date to string and back is successful.
我通过以下方式将其转换为字符串:
I convert it to a string via:
func convertDateToString(date: Date) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return dateFormatter.string(from: date)
}
并通过以下方式将其转换回:
and convert it back via:
func convertStringToDate(string: String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return dateFormatter.date(from: string)!
}
如果您尝试在转换前的日期和之后使用Equatable协议-转换日期说它们不一样。但是,如果将日期转换前后都转换为字符串并进行比较,则它们是相等的。这就是我在前后日期运行XCAssertEqual时的意思:
If you try to use the Equatable protocol on the pre-conversion date and post-conversion date it says they are not the same. However, if you convert both pre and post dates to strings and compare them, they are Equatable. This is what it says when I run XCAssertEqual on pre and post dates:
XCTAssertEqual failed: ("2020-01-22 19:35:40 +0000") is not equal to ("2020-01-22 19:35:40 +0000")
与我看上去很像。我什至尝试将转换前的日期转换为字符串,然后返回以检查日期是否相等并且仍然不相同
Which looks pretty identical to me. I even tried converting the pre-conversion date to a string and back to check if the dates were equal and they still weren't
推荐答案
这里的问题是 Date
存储为 FloatingPoint
值(timeIntervalSinceReferenceDate)。将您的 Date
转换为 String
并返回至 Date
。看看。
The problem there is that Date
is stored as a FloatingPoint
value (timeIntervalSinceReferenceDate). There is fractional seconds being discarded there when converting your Date
to String
and back to Date
. Take a look at post.
这篇关于Swift为什么将日期对象转换为字符串并返回后,它的日期对象(等于)不相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!