Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You would extend DateComponents:

extension DateComponents {
    var millisecond: Int? { 
        guard let nanosecond else { return nil }
        return nanosecond / 1000000
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading