'Firebase TIMESTAMP to date and Time

I am using firebase for my chat application. In chat object I am adding time stamp using Firebase.ServerValue.TIMESTAMP method.

I need to show the message received time in my chat application using this Time stamp .

if it's current time i need to show the time only.It's have days difference i need to show the date and time or only date.

I used the following code for convert the Firebase time stamp but i not getting the actual time.

var timestamp = '1452488445471';
var myDate = new Date(timestamp*1000);
var formatedTime=myDate.toJSON();

Please suggest the solution for this issue



Solution 1:[1]

timestamp is an object

timestamp= {nanoseconds: 0,
seconds: 1562524200}

console.log(new Date(timestamp.seconds*1000))

Solution 2:[2]

Firebase.ServerValue.TIMESTAMP is not actual timestamp it is constant that will be replaced with actual value in server if you have it set into some variable.

mySessionRef.update({ startedAt: Firebase.ServerValue.TIMESTAMP });
mySessionRef.on('value', function(snapshot){ console.log(snapshot.val()) })
//{startedAt: 1452508763895}

if you want to get server time then you can use following code

  fb.ref("/.info/serverTimeOffset").on('value', function(offset) {
    var offsetVal = offset.val() || 0;
    var serverTime = Date.now() + offsetVal;
  });

Solution 3:[3]

In fact, it only work to me when used

firebase.database.ServerValue.TIMESTAMP

With one 'database' more on namespace.

Solution 4:[4]

For those looking for the Firebase Firestore equivalent. It's

firebase.firestore.FieldValue.serverTimestamp()

e.g.

firebase.firestore().collection("cities").add({
    createdAt: firebase.firestore.FieldValue.serverTimestamp(),
    name: "Tokyo",
    country: "Japan"
})
.then(function(docRef) {
    console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
    console.error("Error adding document: ", error);
});

Docs

Solution 5:[5]

inside Firebase Functions transform the timestamp like so:

timestampObj.toDate()
timestampObj.toMillis().toString()

documentation here https://firebase.google.com/docs/reference/js/firebase.firestore.Timestamp

Solution 6:[6]

I know the firebase give the timestamp in {seconds: '', and nanoseconds: ''} for converting into date u have to only do:

  • take a firebase time in one var ex:- const date

and then date.toDate() => It returns the date.

Solution 7:[7]

For Firestore that is the new generation of database from Google, following code will simply help you through this problem.

var admin    = require("firebase-admin");

var serviceAccount = require("../admin-sdk.json"); // auto-generated file from Google firebase.

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount)
});
var db = admin.firestore();

console.log(admin.firestore.Timestamp.now().toDate());

Solution 8:[8]

Solution for newer versions of Firebase (after Jan 2016)

The proper way to attach a timestamp to a database update is to attach a placeholder value in your request. In the example below Firebase will replace the createdAt property with a timestamp:

firebaseRef = firebase.database().ref();
firebaseRef.set({
  foo: "bar", 
  createdAt: firebase.database.ServerValue.TIMESTAMP
});

According to the documentation, the value firebase.database.ServerValue.TIMESTAMP is: "A placeholder value for auto-populating the current timestamp (time since the Unix epoch, in milliseconds) by the Firebase Database servers."

Solution 9:[9]

Here is a safe method to convert a value from firebase Timestamp type to JS Date in case the value is not Timestamp the method returns it as it is

Works for Angular 7/8/9

import firebase from 'firebase';
import Timestamp = firebase.firestore.Timestamp;

export function convertTimestampToDate(timestamp: Timestamp | any): Date | any {
  return timestamp instanceof Timestamp
    ? new Timestamp(timestamp.seconds, timestamp.nanoseconds).toDate()
    : timestamp;
}

Solution 10:[10]

Working with Firebase Firestone 18.0.1 (com.google.firebase.Timestamp)

val timestamp = (document.data["timestamp"] as Timestamp).toDate()

Solution 11:[11]

It is simple. Use that function to get server timestamp as milliseconds one time only:

var getServerTime = function( cb ) {
    this.db.ref( '.info/serverTimeOffset' ).once( 'value', function( snap ) {
      var offset = snap.val();

      // Get server time by milliseconds
      cb( new Date().getTime() + offset );
    });
};

Now you can use it anywhere like that:

getServerTime( function( now ) {
    console.log( now );
});

Why use this way?

According to latest Firebase documentation, you should convert your Firebase timestamp into milliseconds. So you can use estimatedServerTimeMs variable below:

var offsetRef = firebase.database().ref(".info/serverTimeOffset");
offsetRef.on("value", function(snap) {
  var offset = snap.val();
  var estimatedServerTimeMs = new Date().getTime() + offset;
});

While firebase.database.ServerValue.TIMESTAMP is much more accurate, and preferable for most read/write operations, it can occasionally be useful to estimate the client's clock skew with respect to the Firebase Realtime Database's servers. You can attach a callback to the location /.info/serverTimeOffset to obtain the value, in milliseconds, that Firebase Realtime Database clients add to the local reported time (epoch time in milliseconds) to estimate the server time. Note that this offset's accuracy can be affected by networking latency, and so is useful primarily for discovering large (> 1 second) discrepancies in clock time.

https://firebase.google.com/docs/database/web/offline-capabilities

Solution 12:[12]

Try this one,

var timestamp = firebase.firestore.FieldValue.serverTimestamp()
var timestamp2 = new Date(timestamp.toDate()).toUTCString()

Solution 13:[13]

new Date(timestamp.toDate()).toUTCString()

Solution 14:[14]

var date = new Date((1578316263249));//data[k].timestamp
console.log(date);

Solution 15:[15]

Iterating through this is the precise code that worked for me.

querySnapshot.docs.forEach((e) => {
   var readableDate = e.data().date.toDate();
   console.log(readableDate);
}

Solution 16:[16]

    import firebaseAPP from 'firebase/app';


    public Date2firestoreTime(fromDate: Date) {
       return firebaseAPP.firestore.Timestamp.fromDate(fromDate).toMillis()
    }
    public firestoreTime2Date(millisecDate: number) {
       return firebaseAPP.firestore.Timestamp.fromMillis(millisecDate).toDate()
    }


    //usage:
    let FSdatenow = this.Date2firestoreTime(new Date())
    console.log('now to firestore TimeStamp', FSdatenow)
    let JSdatenow = this.firestoreTime2Date(FSdatenow)
    console.log('firestore TimeStamp to Date Obj', JSdatenow)

Solution 17:[17]

For me it works when the timeStamp is an integer rather than a string:

var timestamp = '1452488445471';
var myDate = new Date(parseInt(timestamp));
myDate.toDateString()

Solution 18:[18]

I converted to this format

let timestamp = '1452488445471';
let newDate = new Date(timestamp * 1000)
let Hours = newDate.getHours()
let Minutes = newDate.getMinutes()
const HourComplete = Hours + ':' + Minutes
let formatedTime = HourComplete
console.log(formatedTime)

Solution 19:[19]

let jsDate = new Date(date.seconds * 1000 + date.nanoseconds / 1000000);

Solution 20:[20]

First Of All Firebase.ServerValue.TIMESTAMP is not working anymore for me.

So for adding timestamp you have to use Firebase.database.ServerValue.TIMESTAMP

And the timestamp is in long millisecond format.To convert millisecond to simple dateformat .

Ex- dd/MM/yy HH:mm:ss

You can use the following code in java:

To get the timestamp value in string from the firebase database

String x = dataSnapshot.getValue (String.class);

The data is in string now. You can convert the string to long

long milliSeconds= Long.parseLong(x);

Then create SimpleDateFormat

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy HH:mm:ss");

Now convert your millisecond timestamp to ur sdf format

String dateAsString = sdf.format (milliSeconds);

After that you can parse it to ur Date variable

 date = sdf.parse (dateAsString);

Solution 21:[21]

This code is work for me

<script src="https://www.gstatic.com/firebasejs/4.5.1/firebase.js"></script>
<script>
var config = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: ""
};

firebase.initializeApp(config);
var reff = firebase.database().ref('message');
reff.on('value',haveData, haveerr);
function haveData(datahave){
    var existval= datahave.val();
    var chabi=Object.keys(existval);
    for(var d2=0;d2< chabi.length;d2++){
        var r=chabi[d2];
        var exitval=existval[r].Message;
        var exitval1=existval[r].Name;
        var exit=existval[r].Email;
        var exitval2=existval[r].Subject;
        var timestamp=existval[r].timestamp;
        var sdate=new Date(timestamp);
        var Year=sdate.getFullYear();
        var month=sdate.getMonth()+1;
        var day=sdate.getDate();
        var hh=sdate.getHours();
        var mm=sdate.getMinutes();
        var ss=sdate.getSeconds();
    }
}

function haveerr(e){
     console.log(e);
}
</script>

firebase database