Convert date to timestamp for storing into firebase firestore in javascript

JavascriptFirebaseDateTimestampGoogle Cloud-Firestore

Javascript Problem Overview


I'm currently using Math.floor(Date.now() / 1000) to get the correct timestamp format to add into a document in Firebase, however, the timestamp gets inserted as a number, and not as a timestamp.

number

I would like to have it inserted as shown below (as a timestamp, not as a number).

enter image description here

Is this possible?

Javascript Solutions


Solution 1 - Javascript

You can simply use the following line:

var myTimestamp = firebase.firestore.Timestamp.fromDate(new Date());

.fromDate is a static method from the static Timestamp class from Firebase.

Ref: Firebase Timestamp Doc

Update:

For cloud functions look at JGuo's comment:

> If you are writing cloud functions, it becomes > admin.firestore.Timestamp.fromDate() – JGuo Jan 21 at 1:56

Solution 2 - Javascript

If you want to store a field as a timestamp in Firestore, you'll have to send a JavaScript Date object or a Firestore Timestamp object as the value of the field.

If you want to use Date, simply say new Date(x) where x is the value in milliseconds that you were trying to add before.

If you want to use Timestamp, you would have to do more work to get that x converted into a combination of seconds and nanoseconds to pass to the constructor, as the documentation suggests.

Solution 3 - Javascript

I solved it by using:

const created = firebase.firestore.Timestamp.fromDate(new Date()).toDate();

You have to import firebase from 'firebase/app' explicitly in your code.

import * as firebase from 'firebase/app'

Make sure your created or whatever constant is in type Date before actually being saved to firestore.

Solution 4 - Javascript

As i can see you are doing date added you would be better using the Server Timestamp and using the below security rule to enforce it.

Security Rules

allow create: if request.resource.data.date_added == request.time && 
              // other rules for the message body

Client side JS code

const message = {
    date_added: firebase.firestore.FieldValue.serverTimestamp();
}

Solution 5 - Javascript

To store a date / timestamp in Firestore, you need to send a Date object.

For example, with an existing date, set a field to: new Date("December 10, 1815")

Further information is available in the docs.

Solution 6 - Javascript

This is a bit old but just figure out how to do this in a Svelte project. I assume this would also work in a React project (sorry don't know much about Vue). The kicker is that I am using Web version 9.

import { Timestamp } from "@firebase/firestore";
let noteDate = Timestamp.fromDate(new Date());

Just for context... I am adding this new note object to the UI. When it was just a javascript date it worked fine with firebase but I could not call the required .toDate() without seeing an UI error.

<TimeAgo date={note.NoteDate.toDate()} />

So making this a firebase.Timestamp was my way of avoiding the UI error when calling .toDate on a javascript date object.

Solution 7 - Javascript

This worked out for me (CommonJS)

const {Timestamp} = require("firebase/firestore");

Then

Timestamp.fromDate(new Date())

Solution 8 - Javascript

Late to the game here, but as I read the OP's question it specifically illustrates retaining the timezone offset. Since a timestamp lacks the offset, as the question was asked by the OP it looks like the honest answer is NO.

I have a related situation right now where I need a representation of a specific 'day' but I need the offset. A timestamp with 0s for h/m/s would be ideal except for the lack of offset. I am forced to either add a second field to store the offset, or to do something like a string:

'20200125-360'

Solution 9 - Javascript

Use

 let lang = 'en-US' // you may use user's computer language: navigator.language || navigator.userLanguage
 let d = new Date(date);
 let options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour:"numeric", timeZone:'short' };
 firebase.database().ref('/thePathYouLikeToSave/date_added').set(d.toLocaleDateString(lang, options));

for more options of the date here the full details

Solution 10 - Javascript

This question already have several answer but for the sake of simplicity I explaining it in my way

Kotlin code

val dateObject = Date()
val timestamp = Timestamp(dateObject)

Solution 11 - Javascript

I found a solution thar worked for me when using firebase.firestore.FieldValue.serverTimestamp :

moment(createdAt.toDate().toISOString()).fromNow()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionArjen de JongView Question on Stackoverflow
Solution 1 - JavascriptSean StaynsView Answer on Stackoverflow
Solution 2 - JavascriptDoug StevensonView Answer on Stackoverflow
Solution 3 - JavascriptHasintha AbeykoonView Answer on Stackoverflow
Solution 4 - JavascriptJack WoodwardView Answer on Stackoverflow
Solution 5 - JavascriptJake LeeView Answer on Stackoverflow
Solution 6 - JavascriptBrettView Answer on Stackoverflow
Solution 7 - JavascriptCoder Gautam YTView Answer on Stackoverflow
Solution 8 - JavascriptLove to CodeView Answer on Stackoverflow
Solution 9 - JavascriptHakanCView Answer on Stackoverflow
Solution 10 - JavascriptAZIM MOHAMADView Answer on Stackoverflow
Solution 11 - JavascriptEdmundo Dominguez AgurciaView Answer on Stackoverflow