Bright
Bright

Reputation: 1067

How to convert date to timestamp javascript

Im trying to create a new document in firestore using a cloud function. However i am unable to save the date as a timestamp rather, it's saved as a string currently.

How it is right now

enter image description here

What i need to achieve

enter image description here

Snippet of my cloud function

    await admin.firestore()
    .doc('/buyerProfile/'+response.buyerId)
    .collection('notifications')
    .add({
        'type':'New response',
        'responseId':response.responseId,
        'requestId':response.requestId,
        'date': Date(Date.now()),
        'compressedImgUrl':response.compressedImgUrl,
        'description':response.description,
        'requestPaidFor':request.data().isPaidFor
    }).then(()=>console.log('Notification created'));

Upvotes: 0

Views: 1409

Answers (6)

T.L
T.L

Reputation: 56

import { serverTimestamp } from 'firebase/firestore';

and replace: <'date': Date(Date.now())>

with <'date': serverTimestamp()>

this should solve your problem

Upvotes: 0

Frank van Puffelen
Frank van Puffelen

Reputation: 598847

Firestore stores date/time values in its own Timestamp format.

There are two options:

  1. If you want to capture the client-side time, use Timestamp.now(), so:

    'date': Firestore.Timestamp.now(),
    
  2. If you want to capture the server-side time, use:

    'date': admin.firestore.FieldValue.serverTimestamp(),
    

Upvotes: 0

Bright
Bright

Reputation: 1067

This worked for my case, i had to import Timestamp from firebase admin

const { timeStamp, time } = require("console");
...
'date': timeStamp.now(),

Upvotes: 0

Dharmaraj
Dharmaraj

Reputation: 50840

You don't have new keyword before Date constructor which will indeed return a string. If you want a Date object try this:

date: new Date() // Date object of current time

If you want to store the timestamp as number then pass Date.now()

You can check the same in a browser console:

enter image description here


You can also use serverTimestamp() method instead:

date: admin.firestore.FieldValue.serverTimestamp()

Upvotes: 0

Dawood Ahmad
Dawood Ahmad

Reputation: 474

just do it like this:

      let today = new Date();

  let timestamDate = Date.parse(today) / 1000;

and your date will be converted to timestamp

Upvotes: 0

Tuan Dao
Tuan Dao

Reputation: 2805

You can use to get timestamp new Date().getTime();

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#return_value

Upvotes: 1

Related Questions