目标/问题
我想将Date转换为String,然后返回到Date。我能做到这一点,但我在途中失去了精确性。我如何确保在这个过程中一点也不会丢失呢?
1573827905079978对157382790508
主代码
var now = Date()
var now_as_string = Date.dateAsString(style: .dayMonthYearHourMinuteSecondMillisecondTimezone, date: now)
var back_as_date = Date.stringAsDate(style: .dayMonthYearHourMinuteSecondMillisecondTimezone, string: now_as_string)
print(Date.dateAsTimeIntervalSince1970WithoutDots(date: now))
print(Date.dateAsTimeIntervalSince1970WithoutDots(date: back_as_date))输出
1573827905079978
157382790508
日期扩展(真正魔术发生的地方)
import Foundation
extension Date {
enum Style {
case dayMonthYear
case dayMonthYearHourMinute
case dayMonthYearHourMinuteSecondMillisecondTimezone
}
static func dateAsString(style: Date.Style, date: Date) -> String{
let formatter = DateFormatter()
formatter.dateFormat = fromStyleToString(style: style)
return formatter.string(from: date)
}
private static func fromStyleToString(style: Date.Style) -> String{
switch style {
case .dayMonthYear:
return "dd.MM.yyyy"
case .dayMonthYearHourMinute:
return "dd.MM.yyyy HH:mm"
case .dayMonthYearHourMinuteSecondMillisecondTimezone:
return "dd.MM.yyyy HH:mm:ss:SSS Z"
}
}
static func stringAsDate(style: Date.Style, string: String) -> Date{
let formatter = DateFormatter()
formatter.dateFormat = fromStyleToString(style: style)
return formatter.date(from: string)!
}
static func dateAsTimeIntervalSince1970WithoutDots(date: Date) -> String{
return String(date.timeIntervalSince1970).replacingOccurrences(of: ".", with: "")
}
}发布于 2019-11-15 17:23:43
自引用日期以来,日期仅为数秒,为双倍。(这个别名为"TimeInterval“,但它只是一个双倍。)
如果您希望它是一个不丢失任何信息的字符串,那就是Double的字符串形式:
let nowString = "\(now.timeIntervalSinceReferenceDate)" // "595531191.461246"为了把它转换回来,把它转换成一个日期:
let originalDate = Date(timeIntervalSinceReferenceDate: TimeInterval(nowString)!)
originalDate == now // true你绝对不想删除小数点。这是数字的一个重要部分。
https://stackoverflow.com/questions/58879279
复制相似问题