Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert nanoseconds to milliseconds

I'm trying to get milliseconds from NSCalendarUnit. I was able to get nanosecond, but that has way too many numbers. All I want is 2 numbers. Here is my code:

var startDate = NSDate()
let dateComponents = NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitNanosecond, fromDate: startDate, toDate: NSDate(), options: nil)

let strFraction = String(format: "%02d", dateComponents.nanosecond)
timeLabel.text = "\(strFraction)"

How can I get milliseconds from the NSCalendarUnit?

like image 986
Horay Avatar asked Sep 20 '25 16:09

Horay


1 Answers

As there is no Calendar.Component.millisecond, as opposed to Calendar.Component.nanosecond, we would need to convert from nanoseconds to milliseconds. 1 millisecond is 1000000 nanoseconds, so you would need to divide the number of nanoseconds by 1000000. If you want an integer value, round(nanoseconds/1000000)

like image 56
SentientBacon Avatar answered Sep 22 '25 10:09

SentientBacon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!