ios - 一旦 13 位时间戳保存在 firebase 中,如何在 Xcode 中获取它并将其转换为日期?

标签 ios swift firebase firebase-realtime-database

这是下面的数据库。我需要获取作为时间戳的“标题”子项,并将其转换为 Xcode 中的日期格式。

"UserS" : {
    "K1eqsVZfKGgIf0sS1UZcPNxY62x1" : {
      "Education" : "William Taft Elementary",
      "PhotoPosts" : "https://firebasestorage.googleapis.com/v0/b/daylike-2f938.appspot.com/o/images%2FPhotoPosts?alt=media&token=fd92856e-f7d2-4558-82c4-ee49f580icc5e",
      "caption" : 1563277511065,
      "users" : "jane19@aol.com"
    },

这是我在 super View 下加载的内容。

let databaseRef = Database.database().reference()
    let uid = Auth.auth().currentUser!.uid
    databaseRef.child("UserS").child(uid).child("caption").observeSingleEvent(of: .value, with: { (snapshot) in
        guard let message = snapshot.value as? [String:String] else { return }
        let caption = message["caption"]
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss.SSSSxxx"
        guard let date = dateFormatter.date(from: caption!) else {
        fatalError("ERROR: Date conversion failed due to mismatched format.")
    }
        if (snapshot.exists()){

            print ("mmmmmmm")
        }else{

            print("badddddd")

        }


    })

最后我想以日期格式打印出时间戳,以便我可以检查它是 24 小时前。

最佳答案

“13 位数字时间戳”是自 1970 年 1 月 1 日 UTC 以来的毫秒数

Date 自该时间点以来已经具有时间戳的初始值设定项。唯一的区别是它是 seconds 的数量,而不是 milliseconds

因此,您唯一应该做的就是将其除以 1000:

// skipping unrelevant boilerplate

// assuming caption is Int
let date = Date(timeIntervalSince1970: TimeInterval(caption)/1000.0) // for `1563277511065` it would be `"Jul 16, 2019 at 11:45 AM"`(UTC)

// skipping unrelevant boilerplate

编辑:

要检查时间戳中的日期是否“早于”24 小时,您有多种选择:

  1. 获取 datenow 之间的差异,并检查它是否在 24 小时内:

    let secondsInDay = 86400
    if (-date.timeIntervalSinceNow < secondsInDay) { … } // negative, because that date would be in the past
    
  2. 在使用日历前获取一天:

    let calendar = Calendar.autoupdatingCurrent // or whatever you prefer
    let dayBefore = calendar.date(
                                  byAdding: .day, 
                                  value: -1, 
                                  to: Date(), 
                                  wrappingComponents: true)!
    
    if (date > dayBefore) { … }
    

关于ios - 一旦 13 位时间戳保存在 firebase 中,如何在 Xcode 中获取它并将其转换为日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57058898/

相关文章:

node.js - 在不知道 firebase 和 firebase-admin 中的 key 的情况下如何获得快照的子级

ios - 该应用程序因 xcglogger swift 而崩溃

ios - 屏幕边框和条形按钮项目之间的距离

iphone - Xcode 中的自动布局并保持宽高比

swift - 检索用于用户名签名 firebase 的用户电子邮件

oauth-2.0 - 将 Firebase Google OAuth 身份验证限制为特定用户

ios - 如何保存 touchesBegan touchLocation 值

ios - didReceiveRemoteNotification 函数调用了两次

ios - 让按钮的宽度和高度增长以适合标题文本

ios - SWIFT:当我创建第二个 ViewController 时,如何从原始 ViewController 访问变量