1

Alright I've followed this question verbatim Firebase TIMESTAMP to date and Time and am posting to my Firebase database like this:

function storeUserInfo(username, industry, role, color) {
  if (username != null && industry != null && role != null && color != null) { //use for errors later
    let timestamp = firebase.firestore.FieldValue.serverTimestamp();

    let push = firebase.database().ref('users').push();
    push.set({
      name: username,
      industry: industry,
      role: role,
      color: color,
      date: new Date(timestamp.toDate()).toUTCString()
    });
  }
}

This gives me the error: timestamp.toDate() is not a function

Ive tried several other methods like Firebase.ServerValue.TIMESTAMP but need to get the current formatted date for Firebase database. How can I do this?

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
blue
  • 7,175
  • 16
  • 81
  • 179

1 Answers1

1

You have a couple of things going wrong here. Firstly, you're trying to write to Realtime Database (via firebase.database()), but you're trying to use Firestore's timetamp with it. Firestore and Realtime Database are different databases with different APIs. A Firestore timestamp would not be helpful to you here.

If you want to get a date as reckoned by the client machine's clock, simply call new Date() with no arguments.

    push.set({
      name: username,
      industry: industry,
      role: role,
      color: color,
      date: new Date().toUTCString()
    });

I suggest actually just storing an integer instead of a formatted string - it will probably be easier for you in the long term.

If you want to write an integer value based on the database server's sense of time, you would do this instead, using ServerValue.TIMESTAMP, which gets an actual integer value as soon as the write hits the server:

      date: firebase.database.ServerValue.TIMESTAMP

If you were actually just hoping to get a server timestamp from Firestore's Timestamp API, that's not possible, because the server timestamp can only be calculated on the server. The error is telling you that there is no toDate() method available on the FieldValue type object returned by FieldValue.serverTimestamp(). It doesn't return a Timestamp. It returns a token that you can provide to Firestore that interprets the timestamp on the server and not in the client app. You should provide this token directly to Firestore if you want the server's timestamp in that field:

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441