简体   繁体   English

如何在 Firebase 中获取日期

[英]How to get the date in Firebase

Source code shown below,源代码如下所示,

Database:数据库:

static func insertErrorLog(moduleName: String, message: String) {
    let dateToday = Date()
    let timestamp = Int(Date().timeIntervalSince1970)

    let db = Firestore.firestore()

    let docData: [String: Any] = [
        KDB.Fields.moduleName : moduleName,
        KDB.Fields.message : message,
        KDB.Fields.createdAt : dateToday
    ]

Model:模型:

var uploadedAt: String = ""
var createdAt: String = ""

init(document: DocumentSnapshot) {
    self.key = document.documentID

    let json = JSON(document.data())

    self.storeId = json[KDB.Fields.storeId].stringValue
    self.imgName = json[KDB.Fields.imgName].stringValue
    self.title = json[KDB.Fields.title].stringValue
    self.description = json[KDB.Fields.description].stringValue
    self.sort = json[KDB.Fields.sort].intValue
    self.uploadedAt = json[KDB.Fields.uploadedAt].stringValue
    self.createdAt = json[KDB.Fields.createdAt].stringValue
}

init(key: String, storeId: String, imgName: String, title: String, description: String, sort: Int, uploadedAt: String, createdImageAt: String = "") {
    self.key = key
    self.storeId = storeId
    self.imgName = imgName
    self.title = title
    self.description = description
    self.sort = sort
    self.uploadedAt = uploadedAt
    self.createdAt = createdImageAt
}

Controller:控制器:

    query.getDocuments { (querySnapshot, error) in
        if let error = error {
            SpeedLog.print("Error: \(error.localizedDescription)")
        } else {
            var loop = 1
            for document in (querySnapshot?.documents)! {
                SpeedLog.print("documentDATA:\(document.data())")
                var photoObject = Photo(document: document)
                SpeedLog.print("photoObject:\(photoObject)")

                if (!photoObject.imgName.isEmpty) {
                    let storagePath = "\(photoObject.imgName)"
                    SpeedLog.print("Photo storagePath: \(storagePath)")

                    let storage = Storage.storage()
                    let storageRef = storage.reference()
                    let imageRef = storageRef.child(storagePath)

                    imageRef.getData(maxSize: 1 * 1024 * 1024) { data, error in
                        if let error = error {
                            SpeedLog.print("Photos download image error documentID:\(document.documentID) : \(error.localizedDescription)")
                        } else {
                            photoObject.imageData = UIImage(data: data!)
                            self.photos.append(photoObject)

                            if loop == 1 {
                                self.imageView.image = photoObject.imageData!
                                self.photoTitleLabel.text = "\(photoObject.title)"

                                    self.photoCreatedAtLabel.text = "\(photoObject.createdAt)"
                                    self.photoCreatedAtTitleLabel.isHidden = false
                                //}
                            }
                        }
                        self.collectionView.reloadData()
                        loop += 1
                    }
                }
            }
        }
    }
}

extension PhotoGalleryViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return photos.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CellPhotoGallery", for: indexPath) as! PhotoGalleryCollectionViewCell

    configureCell(cell, atIndexPath: indexPath)

    return cell
}

func configureCell(_ cell: PhotoGalleryCollectionViewCell, atIndexPath indexPath: IndexPath) {

    let photo = photos[indexPath.row]

    if let image = photo.imageData {
        cell.imageView.image = image
    }
    photoLabel.text = photo.title
    photoCreatedAtLabel.text = photo.createdAt
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let photo = photos[indexPath.row]

    if let image = photo.imageData {
        imageView.image = image
    }
    photoLabel.text = photo.title
    photoCreatedAtLabel.text = photo.createdAt
}

In Firebase we have field createdAt: (Timestamp)在 Firebase 中,我们有字段 createdAt: (Timestamp)

Basically, when I run the codes in Xcode the Photo Storage fetch the createdAt from the firebase data but when it comes to Photo Object"self.photoCreatedAtLabel.text = "(photoObject.createdAt)" the date didn't shown. What is the possible missing in the codes? Please see attached of application for reference.基本上,当我在 Xcode 中运行代码时,照片存储从 firebase 数据中获取 createdAt 但是当涉及到 Photo Object"self.photoCreatedAtLabel.text = "(photoObject.createdAt)" 时,日期没有显示。是什么可能缺少代码?请参阅申请附件以供参考。

Edit: added a console printout of the photo object.编辑:添加了照片对象的控制台打印输出。

photoObject:Photo (
   key: "x2q0Asfjn2S8FYr6fIvA", 
   storeId: "", 
   imgName: "locator/stores/egdupo/BitoysVulcanizingandTireShop_rJTM7alkTp_M6L.jpg", 
   imageData: nil, 
   title: "", 
   description: "", 
   sort: 1, 
   uploadedAt: "", 
   createdAt: ""
)

上传日期 2 of 2

Anyone?任何人?

Thank you in advance.先感谢您。

From the FireStore docs来自 FireStore 文档

Currently, Firestore returns timestamp fields as Date but Date only supports millisecond precision, which leads to truncation and causes unexpected behavior when using a timestamp from a snapshot as a part of a subsequent query.目前,Firestore 将时间戳字段返回为日期,但日期仅支持毫秒精度,这会导致截断并在将快照中的时间戳用作后续查询的一部分时导致意外行为。

So if you want to use it, your code needs to handle it as a NSDate (Date) object.所以如果你想使用它,你的代码需要将它作为一个 NSDate (Date) 对象来处理。 however, using the following code但是,使用以下代码

let settings = Firestore.firestore().settings
settings.areTimestampsInSnapshotsEnabled = true

Setting timestampsInSnapshots to true will cause Firestore to return Timestamp values instead of Date, which avoids truncation.将 timestampsInSnapshots 设置为 true 将导致 Firestore 返回 Timestamp 值而不是 Date,从而避免截断。 Note that you must also change any code that uses Date to use Timestamp instead.请注意,您还必须更改任何使用 Date 的代码以使用 Timestamp。

In practice, assume we have a collection of documents and one of the fields in each document is called stamp;在实践中,假设我们有一个文档集合,并且每个文档中的一个字段称为邮票; written like this写成这样

let now = Date()
let stamp = Timestamp(date: now)
self.db.collection("timestamps").document("test_stamp_0").setData( [
   "stamp": stamp
])

to then read that stamp node and format it for output in a UI然后读取该戳节点并将其格式化以在 UI 中输出

//read the document
if let stamp = document.get("stamp") {
    let title = document.documentID
    let ts = stamp as! Timestamp //force downcast stamp to a Timestamp cause' that's what it is.
    let aDate = ts.dateValue()
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
    let formattedTimeZoneStr = formatter.string(from: aDate)
    print(title, formattedTimeZoneStr) //prints test_stamp_0, 2018-10-03 08:00:00 -0400
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM