Difference between timestamp stored and current da

2019-05-23 08:47发布

问题:

I have linked up an app that I have made to an Firebase database.

The app sends Firebase the time as a timeIntervalSinceReferenceDate when a button is pressed. An example of the value is - 498898978852.928.

I want this number to distinguish wether the user has pressed that same button more less than 48 hours ago.

Is there a way to measure the time period of 48 hours or should I use a different method?

I am using swift 2 and Xcode 7!

回答1:

Swift 3. If you are using Swift 2, use 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")
}


回答2:

You are using unix timeStamp*1000 which when casted to Int is used as a timestamp, but since you are going to use it for time manipulations. use this to store your timestamp:-

let timeStamp = NSDate.timeIntervalSinceReferenceDate // Like this only

Make an extension of NSDate outside your class scope

extension NSDate {

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

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

Declaration:-

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

Then in your .observe event firebase function use this: -

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

Check Condition

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

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

    }

For further date manipulation look up :- Difference between two NSDates