1

I need time since Epoch in ms for an API request, so I'm looking to have a function that converts my myUIDatePicker.date.timeIntervalSince1970 into milliseconds by multiplying by 1000. My question is what should the return value be?

Right now I have

func setTimeSinceEpoch(datePicker: UIDatePicker) -> Int {
    return Int(datePicker.date.timeIntervalSince1970 * 1000)
}

Will this cause any issues? I need an integer, not a floating point, but will I have issues with overflow? I tested it out with print statements and it seems to work but I want to find the best way of doing this.

Tommy K
  • 1,759
  • 3
  • 28
  • 51
  • 2
    no idea in swift, but in cocoa land there is something called `NSTimeInterval` – Grady Player May 10 '16 at 15:49
  • 1
    NSTimeInterval is actually a Double, so you could use a Double – Chajmz May 10 '16 at 15:51
  • It's what comes after the decimal you're interested in for milliseconds. You might find some more insight here: http://stackoverflow.com/questions/889380/how-can-i-get-a-precise-time-for-example-in-milliseconds-in-objective-c – Matt Long May 10 '16 at 15:56
  • Assuming that's IEEE 64-bit double-precision floating-point, it can store the current time since 1970 with a precision of about 244 nanoseconds. – Keith Thompson May 10 '16 at 16:12
  • @GradyPlayer `NSTimeInterval` is available in Swift: `public typealias NSTimeInterval = Double` – JAL May 10 '16 at 17:02
  • @Tommy, Mark tour question as solved if so. – brduca May 11 '16 at 11:55

1 Answers1

3

Looking at Apple Docs:

var NSTimeIntervalSince1970: Double { get }

There is a nice function called distantFuture. Even if you use this date in you func the result will be smaller then the max Int.

let future = NSDate.distantFuture() // "Jan 1, 4001, 12:00 AM"
print((Int(future.timeIntervalSince1970) * 1000) < Int.max) // true

So, until 4001 you're good to go. It will work perfectly on 64-bits systems.

Note: If your system supports iPhone 5 (32-bits) it's going to get an error on pretty much any date you use. Int in Iphone 5 corresponds to Int32. Returning an Int64 is a better approach. See this.

Community
  • 1
  • 1
brduca
  • 3,573
  • 2
  • 22
  • 30