Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift ios date as milliseconds Double or UInt64?

I'm not iOS developer but started learning Swift.

I try to convert some logic from Android project to iOS.

I have the following method:

func addGroupItemSample(sample : WmGroupItemSample){ // some custom class

    var seconds: NSTimeInterval = NSDate().timeIntervalSince1970
    var  cuttDate:Double =  seconds*1000;

    var sampleDate: UInt64 = sample.getStartDate(); // <-- problematic place

if(sampleDate > cuttDate){
   // ....
  }
}

From the method above you can see that sample.getStartDate() returns type UInt64.

I thought it's like long in Java: System.currentTimeMillis()

But current time in milliseconds defined as Double.

Is it a proper way to mix Double and UInt64 or do I need to represent all milliseconds as Double only?

Thanks,

like image 376
snaggs Avatar asked Aug 12 '14 11:08

snaggs


People also ask

How to convert Date to milliseconds in iOS Swift?

This is the number of seconds since the 1970 epoch. To convert seconds to milliseconds, you need to multiply the number of seconds by 1000. To convert a Date to milliseconds, you could just call timeIntervalSince1970 and multiply it by 1000 every time.

What is timeIntervalSince1970?

timeIntervalSince1970 is the number of seconds since January, 1st, 1970, 12:00 am (mid night) timeIntervalSinceNow is the number of seconds since now.

What is swift timeIntervalSince1970?

1432233446145 most probably is a time interval given in milliseconds: let date = NSDate(timeIntervalSince1970: 1432233446145.0/1000.0) print("date is \(date)") // date is 2015-05-21 18:37:26 +0000.


2 Answers

in iOS it is better to use double, but if you want to easy port your code and keep it consistent you can try this:

func currentTimeMillis() -> Int64{
    let nowDouble = NSDate().timeIntervalSince1970
    return Int64(nowDouble*1000)
}
like image 74
Ben Avatar answered Oct 01 '22 21:10

Ben


Swift does not allow comparing different types.

seconds is a Double floating point value in seconds with sub-second accuracy.
sampleDate is a UInt64 but the units are not given. sampleDate needs be converted to a Double floating point value with units of seconds.

var sampleDate: Double = Double(sample.getStartDate())

Then they can be compared:

if(sampleDate > cuttDate){}
like image 25
zaph Avatar answered Oct 01 '22 21:10

zaph