How to configure DateFormatter to capture microseconds

后端 未结 4 1922
暗喜
暗喜 2020-12-10 16:03

iOS Date() returns date with at least microsecond precision.
I checked this statement by calling Date().timeIntervalSince1970 which results in

4条回答
  •  遥遥无期
    2020-12-10 16:34

    Solution by @Vlad Papko has some issue:

    For dates like following:

    2019-02-01T00:01:54.3684Z

    it can make string with extra zero:

    2019-02-01T00:01:54.03684Z

    Here is fixed solution, it's ugly, but works without issues:

    override public func string(from date: Date) -> String {
            dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
            let components = calendar.dateComponents(Set([Calendar.Component.nanosecond]), from: date)
    
            let nanosecondsInMicrosecond = Double(1000)
            let microseconds = lrint(Double(components.nanosecond!) / nanosecondsInMicrosecond)
    
            // Subtract nanoseconds from date to ensure string(from: Date) doesn't attempt faulty rounding.
            let updatedDate = calendar.date(byAdding: .nanosecond, value: -(components.nanosecond!), to: date)!
            let dateTimeString = super.string(from: updatedDate)
    
            let stingWithMicroseconds = "\(date.timeIntervalSinceReferenceDate)"
            let dotIndex = stingWithMicroseconds.lastIndex(of: ".")!
            let hasZero = stingWithMicroseconds[stingWithMicroseconds.index(after: dotIndex)] == "0"
            let format = hasZero ? "%@.%06ldZ" : "%@.%6ldZ"
    
            let string = String(format: format,
                                dateTimeString,
                                microseconds)
    
            return string
        }
    

提交回复
热议问题