skip to Main Content

Feels weird to ask a question that’s been asked and answered before, but I did search before posting.

So I want to store a timestamp in Firestore but its either being stored as String or Map, but not as the Timestamp object.

  • new Date() is stored as a String
  • Timestamp.fromDate(new Date()) or simply Timestamp.now() is stored as a Map (seconds and nanoseconds)

I’m importing the method like so:
const { Timestamp } = require("firebase/firestore");

Probably worth mention, this is a cloud function that I’m testing locally via node filename.js

What am I doing wrong?

2

Answers


  1. Firestore does not store JavaScript Date objects. See Supported data types. It appears they store in sub-millisecond resolution high resolution time like window.performance.now(). You should be able to pass a JavaScript Date object as a value though with firebase.firestore.Timestamp.fromDate(new Date());

    Date and time: Chronological: When stored in Cloud Firestore, precise
    only to microseconds; any additional precision is rounded down.

    Login or Signup to reply.
  2. Looking at the documentation on the Timestamp class, a Timestamp stores the date in a second or nanosecond format. Just like you noted, this is why you are not seeing a true Date object stored in the firebase.

    In my general experience, I usually use dates stored as string or timestamp representations in a database. The service getting those date values must convert the fetched data into a data type the service can use. Below are a couple of examples for fetching and storing date data:

    // To store a timestamp using the Timestamp class:
    const date = new Date();
    const timestamp = firebase.firestore.Timestamp.fromDate(date); // 1676660310262
    // store timestamp in database as Timestamp (results in Map)
    
    // Once timestamp is extracted:
    const fetchedTimestamp = 1676660310262
    const fetchedDate = new Date(timestamp) // 'Fri, 17 Feb 2023 18:58:30 GMT'
    
    // To store a string date, use a UTC string to maintain timezone:
    const date = new Date(); // Fri Feb 17 2023 11:58:30 GMT-0700 (Mountain Standard Time)
    const utcDate = date.toUTCString(); // 'Fri, 17 Feb 2023 18:58:30 GMT'
    // store utcDate as a string
    
    // Once date is extracted:
    const fetchedUTCString = 'Fri, 17 Feb 2023 18:58:30 GMT';
    const fetchedDate = new Date(fetchedUTCString) // Fri Feb 17 2023 11:58:30 GMT-0700 (Mountain Standard Time)
    
    

    My recommendation would be to store dates in a Timestamp or string representation. Then in the service reading/writing that data, you should parse the data into a Date object on read and from a Date object to the string/timestamp on a write.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search