在添加到 firestore 之前将 Xcode 中的日期转换为时间戳

Convert a Date in Xcode to timestamp before adding to firestore

我有一个@State var tripDate = Date()

我想添加到 firestore 数据库

  func addData(tripDate: Date) {
        
        // Get a reference to the database
        let db = Firestore.firestore()
        
        // Add a document to a collection
        db.collection("tripDate":tripDate]) { error in
            
            // Check for errors
            if error == nil {
                // No errors
                
                // Call get data to retrieve latest data
                self.getData()
            }
            else {
                // Handle the error
            }
        }
    }

并从 firestore 获取数据

func getData() {
        
        // Get a reference to the database
        let db = Firestore.firestore()
        
        // Read the documents at a specific path
        db.collection("Event").getDocuments { snapshot, error in
            
            // Check for errors
            if error == nil {
                // No errors
                
                if let snapshot = snapshot {
                    
                    // Update the list property in the main thread
                    DispatchQueue.main.async {
                        
                        // Get all the documents and create Todos
                        self.list = snapshot.documents.map { d in
                            
                            // Create a Todo item for each document returned
                            return Event(id: d.documentID,
                                            tripDate: d["tripDate"] as! Date,
            
                                            
                            )
                        }
                    }
                    
                    
                }
            }
            else {
                // Handle the error
            }
        }
    }

这是要添加的按钮

     Button(action: {
     Eventmodel.addData(tripDate: tripDate)
     }) {
     Text("Submit")
}

知道如何在这些情况下将日期转换为时间戳(在这些函数中),因为 Firestore 不采用日期而是采用时间戳,如果我继续将其作为日期,则会发生致命错误并且应用程序崩溃并冻结,任何想法非常感谢!

您可以使用 timeIntervalSince1970 property. If the API you're using supports floating point numbers, you can use it as is, or just convert it to a String. An alternative could be using a DateFormatter.

Date 转换为时间戳

看起来 Swift Firebase 库有一个 class Timestamp 和一个接受 Date:

的初始化器
convenience init(date: Date)

并且有一个函数可以将 Timestamp 转换为 Date:

func dateValue() -> Date

您还可以根据日期手动计算秒和纳秒。这可能看起来像这样:

extension Date {
    var secondsAndNanoseconds: (seconds: Int, nanoseconds: Int) {
      let result = timeIntervalSince1970
      let seconds = Int(result)
      return (seconds, Int(1000000000 * (result-Double(seconds))))
    }
}