Trying to convert Firebase timestamp to NSDate in

2019-01-05 01:10发布

I'm trying to use Firebase timestamps in a Swift app. I'd like to store them in my Firebase, and use them as native NSDate objects in my app.

The docs say they are unix epoch time, so I've tried:

NSDate(timeIntervalSince1970:FirebaseServerValue.timestamp)

with no luck.

This:

FirebaseServerValue.timestamp

returns

0x00000001199298a0

according to the debugger. What is the best way to pass these timestamps around?

9条回答
Root(大扎)
2楼-- · 2019-01-05 01:54

Firestore has an API for this --> -(NSDate *)dateValue

For example, if you have saved(set) a new document with a field "createdAtDate"

    NSDictionary *dataToBeSaved = @{
        //Tell the server to save FIRTimestamps when the document is created
        @"createdAtDate":[FIRFieldValue fieldValueForServerTimestamp],
        @"lastModifiedDate":[FIRFieldValue fieldValueForServerTimestamp],

       //Other fields
       @"userName":@"Joe Blow"
    }

    [myFirReference setData:[dataToBeSaved]
                    options:[FIRSetOptions merge]
                 completion:^(NSError* error) {
  }

You can get back this information either with a get query or via setting a listener. When you have the snapshot back, just access the dates you saved and convert to NSDate.

  NSDate *date1 = [snapshot.data[@"createdAtDate"] dateValue];
  NSDate *date2 = [snapshot.data[@"lastModifiedDate"] dateValue];

There will be a slight loss in precision, but as most people use dates for data synchronization or sorts, I can't think of a case where the loss of precision would be an issue.

查看更多
Emotional °昔
3楼-- · 2019-01-05 01:54

You can get a date approximation from Firebase. For example if you're trying to change a firebase user's creation date (a Timestamp) to a Date:

user.creationDate.dateValue()
查看更多
男人必须洒脱
4楼-- · 2019-01-05 02:03

You will get the right time if you use:

let timestamp = FIRServerValue.timestamp()

let converted = NSDate(timeIntervalSince1970: timestamp / 1000)


let dateFormatter = NSDateFormatter()
dateFormatter.timeZone = NSTimeZone.localTimeZone()
dateFormatter.dateFormat = "hh:mm a"
let time = dateFormatter.stringFromDate(converted)
查看更多
登录 后发表回答