我需要返回与日期字符串相同的日期字符串,但是将其转换为日期并返回后丢失了几个字符
var dateStr = "2019-08-02T11:46:46.5117312Z"
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
let date = formatter.date(from: dateStr)
var str = formatter.string(from: date!) // ===>>> "2019-08-02T11:46:46.511Z"
答案 0 :(得分:0)
您可以使用自定义格式化程序来实现。但是请注意,Double
精度不足以存储日期。结果是2019-08-02T11:46:46.511731 1 Z。代码:
class CustomDateFormatter {
private let dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
return formatter
}()
func date(fromString str: String) -> Date? {
let strs = str.components(separatedBy: CharacterSet(charactersIn: ".Z"))
if strs.count != 3 {
return nil
}
let dateStr = strs[0]
let secondsStr = strs[1]
guard let date = dateFormatter.date(from: dateStr),
let seconds = Double("0."+secondsStr) else {
return nil
}
let timeinteval = date.timeIntervalSince1970 + seconds
return Date(timeIntervalSince1970: timeinteval)
}
func string(fromDate date: Date) -> String {
let clippedDate = Date(timeIntervalSince1970: floor(date.timeIntervalSince1970))
let seconds = date.timeIntervalSince1970.truncatingRemainder(dividingBy: 1)
var lastPart = String(format: "%.7f", seconds)
lastPart = (lastPart as NSString).substring(from: 1)
return "\(dateFormatter.string(from: clippedDate))\(lastPart)Z"
}
}
let dateStr = "2019-08-02T11:46:46.5117312Z"
let formatter = CustomDateFormatter()
let date = formatter.date(fromString: dateStr)!
print(formatter.string(fromDate: date)) // =====>> 2019-08-02T11:46:46.5117311Z