Timestamp and dates
list of interactions
-
client SDK ↔ cloud function
-
client SDK ↔ firestore database
-
admin SDK ↔ firestore database
list of representation
Date object: clientSDK, adminSDK
Timestamp object: clientSDK, adminSDK, firestore
ISO string: clientSDK, adminSDK, firestore
(client SDK, adminSDK) ↔ firestore database
The SDK (client or admit) transforms a Date field or a Timestamp field into a timestampValue ISO date string, before sending it to Firestore.
JS object to send
const docRef = await addDoc(collection(db, "users"), {
first: "John",
last: "Appleseed",
born: 1899,
currentDate: new Date(),
})
JSON payload: (double quotes stripped)
const payload = {
streamToken: "MA==",
writes: [
{
update: {
name: "projects/fir-9-demo-b106a/databases/(default)/documents/users/hreijX....bXuvinA0",
fields: {
first: { stringValue: "John" },
last: { stringValue: "Appleseed" },
born: { integerValue: "1899" },
currentDate: { timestampValue: "2023-10-07T18:47:13.279000000Z" },
},
},
currentDocument: { exists: false },
},
],
}
Alternative with Timestamp object:
import { Timestamp } from "firebase/firestore"
currentDate: Timestamp.now()
JSON payload
currentDate: { "timestampValue": "2023-10-07T19:20:40.438000000Z" }
As we retrieve the property from Firestore: the Client/Admin SDK receive it as a Timestamp JSON and instantiate it as a Timestamp object.
The received object date field is a Timestamp object regardless if we sent a Date object.
Alternative with ISO string:
currentDate: new Date().toISOString()
JSON payload
currentDate: {
stringValue: "2023-10-07T18:52:37.995Z"
}
client SDK ↔ cloud function
Send a Date or an ISO string date to the cloud function through request data: the cloud function receives an ISO string.
Send a Timestamp to the cloud function through request data: the cloud function receives a record object with two properties: seconds and nanoseconds.
date: '2023-10-08T07:54:47.527Z',
isoStringDate: '2023-10-08T07:54:47.527Z'
receivedTimestamp: { seconds: 1696751687, nanoseconds: 527000000 },
As such, the cloud function must manually instantiate either a Date or a Timestamp from the raw data it receives from the ISO string or from the Timestamp object.
instanciate a Timestamp on cloud functions
new Timestamp(receivedTimestamp.seconds, receivedTimestamp.nanoseconds)
instanciate a Date
new Date(date)
new Date(isoStringDate)
new Date(receivedTimestamp.seconds * 1000)
In the response
date
the server does not send Date fields to the client.
We must transform the date field to a number (getTime()) or as a string (toJSON()) on the server before sending it back, and then parse back to a Date manually on the client.
timestamp
the server sends a Timestamp field to the client, but it transforms it to a two-properties record that contains _seconds and _nanoseconds.
We may transform the timestamp field to a number (toMillis()), send it, then parse back to a Timestamp on the client.