88

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

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Kichu
  • 1,641
  • 4
  • 21
  • 28

23 Answers23

54

A Timestamp is an object:

timestamp = {
  nanoseconds: 0,
  seconds: 1562524200
}

console.log(new Date(timestamp.seconds*1000))
Philippe Fanaro
  • 6,148
  • 6
  • 38
  • 76
vineet
  • 850
  • 7
  • 9
  • I think this is what the user us asking – Chukwuemeka Maduekwe Nov 12 '20 at 05:09
  • Totally works and returns date in - Day (alphabetic ) month (alphabetic ) date (numerical) year (numerical) time (hh:mm) and Time zone (GMT+ ..). Thanks – Suyash Vashishtha Aug 07 '21 at 11:58
  • 1
    Why do you multiply seconds * 1000? Thank you – Rodius Apr 09 '22 at 16:29
  • 2
    `new Date(milliseconds)` the function accepts ms, to convert seconds to ms we multiply by 1000 https://www.w3schools.com/js/js_dates.asp#:~:text=minutes%2C%20seconds%2C%20milliseconds)-,new%20Date(milliseconds),-new%20Date(date – vineet Apr 09 '22 at 23:47
36

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;
  });
Bek
  • 3,157
  • 1
  • 17
  • 28
  • 2
    If you do `console.log(new Date(snapshot.val()))`, you'll see the date as a string. `var date = new Date(snapshot.val())` will give you the date in an object that you can call useful functions on: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date – Frank van Puffelen Jan 11 '16 at 17:26
28

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

Dan Alboteanu
  • 9,404
  • 1
  • 52
  • 40
23

In fact, it only work to me when used

firebase.database.ServerValue.TIMESTAMP

With one 'database' more on namespace.

Tiago Gouvêa
  • 15,036
  • 4
  • 75
  • 81
  • 2
    but it use the format like 1486106680368 how can i convert it into date and time – Ayaz Ahmad Tarar Feb 03 '17 at 07:27
  • @AyazAhmadTarar if you are using angular, can simply use their built in pipes such as 'Date', or use angular2-moment to easily convert the timestamp – William Wu Jul 16 '17 at 17:09
  • @WilliamWu but it will use the CLIENT timestamp.. not? The firebase ServerValue.TIMESTAMP ensure that it's the "real" time from server. – Tiago Gouvêa Jul 17 '17 at 14:12
23

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

Kyle Finley
  • 11,842
  • 6
  • 43
  • 64
  • I am trying to use this solution however I get the following error - ReferenceError: firebase is not defined. I am using js – Rahul Bagal Feb 16 '19 at 05:47
  • 1
    Rahul, it sounds like you don't have the firebase library installed or loaded. Are you using the web version or the Node JS version? https://firebase.google.com/docs/firestore/quickstart – Kyle Finley Feb 16 '19 at 16:26
  • 1
    I found that by adding a new field name 'createdAt' to a 'timestamp' value, it automatically creates a timestamp for all documents – kai_onthereal May 22 '19 at 08:44
9

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());
zemunkh
  • 662
  • 7
  • 13
9

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.

41 72 6c
  • 1,600
  • 5
  • 19
  • 30
ANKIT MISHRA
  • 558
  • 4
  • 13
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."

Matt
  • 5,800
  • 1
  • 44
  • 40
6

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;
}
Sergiy Seletskyy
  • 16,236
  • 7
  • 69
  • 80
6

Try this one,

var timestamp = firebase.firestore.FieldValue.serverTimestamp()
var timestamp2 = new Date(timestamp.toDate()).toUTCString()
Codemaker2015
  • 12,190
  • 6
  • 97
  • 81
5

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

val timestamp = (document.data["timestamp"] as Timestamp).toDate()
rockdaswift
  • 9,613
  • 5
  • 40
  • 46
4

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

kuzey beytar
  • 3,076
  • 6
  • 37
  • 46
2

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

Borovske
  • 33
  • 5
2
    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)
Aydın Candan
  • 31
  • 1
  • 3
1

var date = new Date((1578316263249));//data[k].timestamp
console.log(date);
user3156040
  • 723
  • 5
  • 5
1

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

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

Michael Nelles
  • 5,426
  • 8
  • 41
  • 57
1

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()
Nat
  • 135
  • 4
0

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)
0
let jsDate = new Date(date.seconds * 1000 + date.nanoseconds / 1000000);
Zrelli Majdi
  • 1,204
  • 2
  • 11
  • 16
0

You might have to specify the type to use .toDate() like this;

import { Timestamp } from "firebase/firestore";
...
(dateVariable as unknown as Timestamp).toDate()

This was .toDate() works as intended.

Akshay K Nair
  • 1,107
  • 16
  • 29
-1

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);
Doge
  • 853
  • 11
  • 35
-1

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

André Kool
  • 4,880
  • 12
  • 34
  • 44
-12

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

Convert it:

var timestamp = '1452488445471';
var myDate = new Date(timestamp).getTime();
trincot
  • 317,000
  • 35
  • 244
  • 286
Jude Ben
  • 7
  • 6
  • 1
    Firebase.ServerValue.TIMESTAMP is a Firebase constant value not a UNIX timestamp. – Matt Jensen Oct 11 '16 at 00:53
  • the return value after setting it in the database is a UNIX timestamp but the actual command is not, so while yes at some point they resolve to the same thing and can be thusly converted, one must be careful to not try an duse the Firebase timestamp value the same way they would the getTime function in an operation. – Tope Mar 11 '17 at 21:32