How to change second and nanoseconds to firestore timestamp format using Firebase cloud functions

Vijay Rahul
1 min readApr 19, 2020

--

When we export the data on json file from cloud firestore database, the Timestamp format is converted to”_seconds”: 1556530679, “_nanoseconds”: 6700000000, and when we again import that json file to cloud firestore database, it is imported as Seconds and nanoseconds.

To overcome this, we can use this cloud function for not changing the time stamp format. Then, the Timestamp format is Monday, 29 April 2019 15:07:59 GMT+05:30.

Below is a code snippet to implement this functionality,

const functions = require('firebase-functions');
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);
exports.Timestampcreation = functions.region('Your-Region')
.firestore.document('CollectionName/{DocumentID}') //InitiateCollectionName and DocumentIdName
.onCreate((snap, context) => {
const DocId = context.params.Id;
const data = snap.data();
console.log(snap.data());
console.log(data.Created_At); //data.fieldname1
console.log(data.Updated_At); //data.fieldname2
const createddate = new admin.firestore.Timestamp(data.Created_At._seconds, data.Created_At._nanoseconds) //As Timestamp is under firebase.firestore namespace
const updateddate = new admin.firestore.Timestamp(data.Updated_At._seconds, data.Updated_At._nanoseconds)
console.log(createddate);
console.log(updateddate);
const TimestampRef = admin.firestore().collection(CollectionName).doc(DocId);
return TimestampRef.update({
Created_At: createddate,
Updated_At: updateddate
});
});

--

--