Arjen de Jong
Arjen de Jong

Reputation: 1121

Convert date to timestamp for storing into firebase firestore in javascript

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?

Upvotes: 86

Views: 102709

Answers (11)

Coder Gautam YT
Coder Gautam YT

Reputation: 2147

The best way is to use the Timestamp class provided by Firebase

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

Then

Timestamp.fromDate(new Date())

Upvotes: 6

Hasintha Abeykoon
Hasintha Abeykoon

Reputation: 524

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.

Upvotes: 9

Brett
Brett

Reputation: 836

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.

Upvotes: 13

AZIM MOHAMAD
AZIM MOHAMAD

Reputation: 72

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)

Upvotes: -2

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

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

Upvotes: -3

Sean Stayns
Sean Stayns

Reputation: 4234

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

Upvotes: 138

Love to Code
Love to Code

Reputation: 463

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'

Upvotes: 0

Doug Stevenson
Doug Stevenson

Reputation: 317467

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.

Upvotes: 20

Cappittall
Cappittall

Reputation: 3441

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

Upvotes: -2

Jack Woodward
Jack Woodward

Reputation: 1001

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();
}

Upvotes: 7

Jake Lee
Jake Lee

Reputation: 7979

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.

Upvotes: 6

Related Questions