【问题标题】:Difference between timestamp stored and current date存储的时间戳与当前日期之间的差异
【发布时间】:2016-10-23 09:42:32
【问题描述】:

我已将自己制作的应用链接到 Firebase 数据库。

当按下按钮时,应用会以 timeIntervalSinceReferenceDate 的形式向 Firebase 发送时间。该值的一个示例是 - 498898978852.928

我想要这个数字来区分用户是否在不到 48 小时前按下了同一个按钮。

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

我正在使用 swift 2 和 Xcode 7!

【问题讨论】:

  • 为什么将 Firebase 作为标签包含在内?

标签: swift xcode firebase swift2 nstimeinterval


【解决方案1】:

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")
}

【讨论】:

    【解决方案2】:

    您正在使用 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

    【讨论】:

    • 我已经尝试过了,但在代码的扩展部分返回错误'使用未声明的类型'日期'
    • 现在日历也在做同样的事情
    • 有什么方法可以修复这个错误@Dravidian – Sam 13 分钟前
    • TimeInterval改为timeInterval,希望这是最后一个语法错误
    猜你喜欢
    • 1970-01-01
    • 2016-06-22
    • 1970-01-01
    • 2019-01-24
    • 2014-03-05
    • 1970-01-01
    • 2021-01-23
    • 1970-01-01
    • 2011-12-10
    相关资源
    最近更新 更多