[javascript] 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

This question is related to javascript angularjs firebase

The answer is


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

    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)

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)

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


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


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;
}

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 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."


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

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


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.


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


Firebase.ServerValue.TIMESTAMP is the same as new Date().getTime().

Convert it:

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

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

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

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


In fact, it only work to me when used

firebase.database.ServerValue.TIMESTAMP

With one 'database' more on namespace.


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


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


timestamp is an object

_x000D_
_x000D_
timestamp= {nanoseconds: 0,_x000D_
seconds: 1562524200}_x000D_
_x000D_
console.log(new Date(timestamp.seconds*1000))
_x000D_
_x000D_
_x000D_


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

Try this one,

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to angularjs

AngularJs directive not updating another directive's scope ERROR in Cannot find module 'node-sass' CORS: credentials mode is 'include' CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 Print Html template in Angular 2 (ng-print in Angular 2) $http.get(...).success is not a function Angular 1.6.0: "Possibly unhandled rejection" error Find object by its property in array of objects with AngularJS way Error: Cannot invoke an expression whose type lacks a call signature

Examples related to firebase

How can I solve the error 'TS2532: Object is possibly 'undefined'? Getting all documents from one collection in Firestore FirebaseInstanceIdService is deprecated Failed to resolve: com.google.firebase:firebase-core:16.0.1 NullInjectorError: No provider for AngularFirestore Firestore Getting documents id from collection How to update an "array of objects" with Firestore? firestore: PERMISSION_DENIED: Missing or insufficient permissions Cloud Firestore collection count iOS Swift - Get the Current Local Time and Date Timestamp