Firebase TIMESTAMP to date and Time

JavascriptAngularjsFirebaseFirebase Realtime-Database

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

timestamp is an object

timestamp= {nanoseconds: 0,
seconds: 1562524200}

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

Solution 2 - Javascript

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 - Javascript

In fact, it only work to me when used

firebase.database.ServerValue.TIMESTAMP

With one 'database' more on namespace.

Solution 4 - Javascript

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 - Javascript

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 - Javascript

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 - Javascript

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 - Javascript

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 - Javascript

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 - Javascript

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

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

Solution 11 - Javascript

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 - Javascript

Try this one,

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

Solution 13 - Javascript

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

Solution 14 - Javascript

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

Solution 15 - Javascript

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 - Javascript

    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 - Javascript

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 - Javascript

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 - Javascript

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

Solution 20 - Javascript

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 - Javascript

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

Solution 22 - Javascript

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

Convert it:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKichuView Question on Stackoverflow
Solution 1 - JavascriptvineetView Answer on Stackoverflow
Solution 2 - JavascriptBekView Answer on Stackoverflow
Solution 3 - JavascriptTiago GouvêaView Answer on Stackoverflow
Solution 4 - JavascriptKyle FinleyView Answer on Stackoverflow
Solution 5 - JavascriptDan AlboteanuView Answer on Stackoverflow
Solution 6 - JavascriptANKIT MISHRAView Answer on Stackoverflow
Solution 7 - JavascriptzemunkhView Answer on Stackoverflow
Solution 8 - JavascriptMattView Answer on Stackoverflow
Solution 9 - JavascriptSergiy SeletskyyView Answer on Stackoverflow
Solution 10 - JavascriptrockdaswiftView Answer on Stackoverflow
Solution 11 - Javascriptkuzey beytarView Answer on Stackoverflow
Solution 12 - JavascriptCodemakerView Answer on Stackoverflow
Solution 13 - JavascriptBorovskeView Answer on Stackoverflow
Solution 14 - Javascriptuser3156040View Answer on Stackoverflow
Solution 15 - JavascriptMichael NellesView Answer on Stackoverflow
Solution 16 - JavascriptAydın CandanView Answer on Stackoverflow
Solution 17 - JavascriptNatView Answer on Stackoverflow
Solution 18 - Javascriptuser12881178View Answer on Stackoverflow
Solution 19 - JavascriptZrelli MajdiView Answer on Stackoverflow
Solution 20 - JavascriptDogeView Answer on Stackoverflow
Solution 21 - JavascriptRizwan HaqueView Answer on Stackoverflow
Solution 22 - JavascriptJude BenView Answer on Stackoverflow