存储的时间戳与当前日期之间的差异

时间:2016-10-23 09:42:32

标签: swift xcode firebase swift2 nstimeinterval

我已将我所做的应用与Firebase数据库相关联。

当按下按钮时,应用会将Firebase的时间作为timeIntervalSinceReferenceDate发送。值的一个示例是 - 498898978852.928

我希望这个号码能够区分用户在48小时前按下相同的按钮。

有没有办法测量48小时的时间段,还是应该使用不同的方法?

我正在使用swift 2和Xcode 7!

2 个答案:

答案 0 :(得分:3)

Swift 3.如果您使用的是Swift 2,请使用NSDate

//the first button press, this is a double but assume it's a timeInterval
let firstPress = 498898978.928 

let date = Date()

let secondPress = date.timeIntervalSinceReferenceDate //the second button press

let diffInSeconds = secondPress - firstPress //total time difference in seconds

let hours = diffInSeconds/60/60 //hours=diff in seconds / 60 sec per min / 60 min per hour

if hours < 48 {
     print("less then 48 hours difference")
} else {
     print("greater/equal to 48 hours difference")
}

答案 1 :(得分:1)

您正在使用 unix timeStamp * 1000 ,当将其转换为Int时用作时间戳,但由于您将使用它进行时间操作。用它来存储你的时间戳: -

let timeStamp = NSDate.timeIntervalSinceReferenceDate // Like this only

在课程范围之外扩展 NSDate

extension NSDate {

 func daysFromTheDate(date: NSDate) -> Int {
    return NSCalendar.currentCalendar().components(.Day, fromDate: date, toDate: self, options: []).day
}
}

class  yourViewController : UIViewController,.. {
 ...
  }

声明: -

 let date1 = NSDate() // Declare the variable globally

然后在 .observe 事件中,firebase函数使用: -

 var retrieved_timeStamp = ... // timeStamp that you retrieve from firebase
 var date = NSDate(timeIntervalSinceReferenceDate: timeInterval(retrieved_timeStamp)) 
 print(date1.daysFromTheDate(from: date as NSDate))

检查条件

if date1.daysFromTheDate(from: date as NSDate) >= 2{

         //48 or more hours have passed now, Do the Job. Bingo!..       

    }

进一步查看日期: - Difference between two NSDates