0

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'));

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Bright
  • 707
  • 2
  • 10
  • 22

6 Answers6

1

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

Tuan Dao
  • 2,647
  • 1
  • 10
  • 20
0

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()
Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
0

just do it like this:

      let today = new Date();

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

and your date will be converted to timestamp

Dawood Ahmad
  • 476
  • 4
  • 13
0

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

const { timeStamp, time } = require("console");
...
'date': timeStamp.now(),
Bright
  • 707
  • 2
  • 10
  • 22
0

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(),
    
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
0

import { serverTimestamp } from 'firebase/firestore';

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

with <'date': serverTimestamp()>

this should solve your problem

T.L
  • 56
  • 3