How to configure DateFormatter to capture microseconds

后端 未结 4 1928
暗喜
暗喜 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:26

    The resolution of (NS)DateFormatter is limited to milliseconds, compare NSDateFormatter milliseconds bug. A possible solution is to retrieve all date components (up to nanoseconds) as numbers and do a custom string formatting. The date formatter can still be used for the timezone string.

    Example:

    let date = Date(timeIntervalSince1970: 1490891661.074981)
    
    let formatter = DateFormatter()
    formatter.dateFormat = "ZZZZZ"
    let tzString = formatter.string(from: date)
    
    let cal = Calendar.current
    let comps = cal.dateComponents([.year, .month, .day, .hour, .minute, .second, .nanosecond],
                                   from: date)
    let microSeconds = lrint(Double(comps.nanosecond!)/1000) // Divide by 1000 and round
    
    let formatted = String(format: "%04ld-%02ld-%02ldT%02ld:%02ld:%02ld.%06ld",
                           comps.year!, comps.month!, comps.day!,
                           comps.hour!, comps.minute!, comps.second!,
                           microSeconds) + tzString
    
    print(formatted) // 2017-03-30T18:34:21.074981+02:00
    

提交回复
热议问题