Difeng Chen
Difeng Chen

Reputation: 159

How to get the timestamp from servervalue?

I'm trying to get the server time from the firebase with the following code:

let timestamp = ServerValue.timestamp()
let today = NSDate(timeIntervalSince1970: timestamp/1000)

But this gives me an error saying:

Binary operator '/' cannot be applied to operands of type '[Any Hashable: Any]' and 'Int'

Why ServerValue.timestamp() dosen't return a TimeIntervel value? How can I get the server's local time?

Upvotes: 0

Views: 1017

Answers (2)

Shivakumar
Shivakumar

Reputation: 110

I'm not sure how to get the timestamp from servervalue but the error is being thrown because the convenience init(timeIntervalSince1970 secs: TimeInterval) you are using to create the date is expecting the secs to be in TimeInterval which is Double and to pass that you are trying to divide a type which is not permitted (timestamp/1000).

Below is an example of how your double value should be to get it working

let unixTimestamp = 1480134638.0
let date = Date(timeIntervalSince1970: unixTimestamp)

print(date) -> "2016-11-26 04:30:38 +0000\n"

Upvotes: 0

Utkarsh Bhatt
Utkarsh Bhatt

Reputation: 1606

You can't use the ServerValue.TIMESTAMP to get the Firebase's server time.

It maps to the Firestore timestamp value for the server time when you write it to a document.

If you want the server time, there are two ways.

  1. Write the ServerValue.TIMESTAMP to a temporary doc in Firestore and read it from there.

  2. Use a Google Cloud function to get an instance of Date() object as a string in response.end() method. Create an HTTP endpoint like this. You can then use an AJAX request to get the result.

const app = (req, res) => { // this will return the Firebase server time res.send(new Date()); };

Upvotes: 1

Related Questions