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
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 );
});
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;
});
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:
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);
});
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>
var date = new Date((1578316263249));//data[k].timestamp_x000D_
console.log(date);
_x000D_
timestamp is an object
timestamp= {nanoseconds: 0,_x000D_
seconds: 1562524200}_x000D_
_x000D_
console.log(new Date(timestamp.seconds*1000))
_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()
Source: Stackoverflow.com