swiftdate

Calendar.current.dateComponents() return milliseconds


I'm using Calendar.current.dateComponents([.second], from: .now, to: timerEnd) to return the end time for a timer within my app. The issue I'm having is that I want to display milliseconds after the remaining times is less than a second. The following code works but I do not like having to run calculations on nanoseconds directly in my call, I would rather just be able to use timeToEnd.milliseconds

let timeToEnd = Calendar.current.dateComponents(
    [.second, .nanosecond], 
    from: .now, 
    to: timerEnd // Just a Date() object
)

return "\((timeToEnd.nanosecond! / 1000000))"

Is there a way I can just extend Date or Calendar to access timeToEnd.milliseconds?


Solution

  • You would extend DateComponents:

    extension DateComponents {
        var millisecond: Int? { 
            guard let nanosecond else { return nil }
            return nanosecond / 1_000_000
        }
    }