Michel
Michel

Reputation: 11753

Handling a time-stamp in Firebase

In firebase realtime database, something seemingly basic does not work.

Here is the JS code:

  let myDBRef = firebase.database().ref('MyCollection');
  newItem = myDBRef.push(),
  startTime = firebase.database.ServerValue.TIMESTAMP,
  endTime = startTime + 24*3600*1000
  newItem.set({
    someField:'myFieldValue',
    startTime:startTime,
    endTime:endTime
  });

I expect something like the following in the DB as a result:

  -MXb9s2-3mX3XZL_azRv
      endTime: 1601691254295
      someField: "myFieldValue"
      startTime: 1601604854295

But I get this instead:

  -MXb9s2-3mX3XZL_azRv
      endTime: "[object Object]86400000"
      someField: "myFieldValue"
      startTime: 1601604854295

What am I doing wrong and how do I need to change the JS code to get the result I expect?

Upvotes: 0

Views: 100

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598740

The firebase.database.ServerValue.TIMESTAMP is not the current server-side timestamp, but a marker value that gets translated to the actual server-side timestamp when written to the database.

That means that you can't store calculated values like you do now in a single step. You have two options:

  1. Store the duration instead of the endTime. So:

    let myDBRef = firebase.database().ref('MyCollection');
    newItem = myDBRef.push(),
    startTime = firebase.database.ServerValue.TIMESTAMP,
    duration = 24*3600*1000
    newItem.set({
      someField:'myFieldValue',
      startTime:startTime,
      duration:duration
    });
    
  2. Store the startTime first, and then calculate the endTime either in the client or in a Cloud Function, that then updates the database. This'd be something like:

    let myDBRef = firebase.database().ref('MyCollection');
    newItem = myDBRef.push(),
    startTime = firebase.database.ServerValue.TIMESTAMP,
    duration = 24*3600*1000
    newItem.set({
      someField:'myFieldValue',
      startTime:startTime,
    }).then(() => {
      newItem.child("startTime").once("value").then((snapshot) => {
        newItem.update({ endTime: snapshot.val() + duration });
      })
    })
    

Upvotes: 1

Related Questions