angularfire retrieving data timestamp to timestamp - javascript

I am trying to retrieve data using angularfire .I.e retrieve all data in an array from one timestamp to another timestamp.
var messageOfEachUser =firebase.database().ref().child("messages").child(data.key);
var currentTime = firebase.database.ServerValue.TIMESTAMP;
var query = messageOfEachUser.queryOrderedByChild("time").queryStartingAtValue(currentTime).queryEndingAtValue(lastSeenValueFromNode);
var listOfNewMessages = $firebaseArray(query);
console.log(listOfNewMessages);
Here in the above code connection to firebase. And querying data from a currenTime to lastSeenValueFromNode where lastSeenValueFromNode contains a timestamp when a user visited this node last time.

You cannot user firebase.database.ServerValue.TIMESTAMP in the way you are doing here. It is really just a marker value, that will be converted into the actual timestamp when your operation reaches the server.
Since you are using timestamps, you can simply use the local time as a rough estimate:
var currentTime = Date.now();
Alternatively, you can use Firebase's built-in latency detection value and get a value that is closer to ServerValue.TIMESTAMP:
var offsetRef = firebase.database().ref(".info/serverTimeOffset");
offsetRef.on("value", function(snap) {
var offset = snap.val();
var currentTime = Date.now() + offset;
});

Related

BSON.Timestamp conversion issue in Nodejs Mongodb Stitch?

I am using stitch function to get the last 7 days from event collection.below is my code.this is execute in stitch function.
exports = async function() {
var events = context.services.get("mongodb-atlas").db("utilo").collection("events");
var today = new Date();
var lastWeek = BSON.Timestamp(today.setDate(today.getDate()-7),0);
console.log(lastWeek);
var document = null;
do{
document = await cursor.next();
if(document){
var result = {};
result.community = document._id;
result.data.newUsersCount = await events.count({community:document._id,type:"join",status:"completed",ts:{$gt:lastWeek}});
}}
}
In the above code, I tried to get last 7 days records from event collection.Here (today.setDate(today.getDate()-7),0) getting the correct Timestamp value but after adding BSON.Timestamp, the timestamp will change to lower year or higher year like either 2004 or 2024. without changing the Timestamp value, can we convert to the Timestamp?
How can i store value in last week like TImestamp(1520801145,0)?
or How to write the code for get the last 7 days record from events collection (ts stored in timestamp)

Firebase getting server timestamp

I am trying to structure my firebase database as such.
year/month/date/message
e.g. 2017/08/26/message
Therefore, I need to get the firebase server time to set the new message reference path.
I have used Firebase.database.ServerValue.TIMESTAMP but it returns a placeholder that only gets converted to epoch time during inserting. Therefore my 'createdAt' field is correct. But I need a way to create my desired path structure.
let epoch = Firebase.database.ServerValue.TIMESTAMP
console.log(`epoch : ${epoch}`) // it returns an object
let date = new Date(epoch) // date creation fail here
console.log(`date : ${date}`)
let messagesRef = db.ref(`messages/${date.getFullYear()}/${date.getMonth()}/${date.getDate()}`)
let newMessage = {
createdAt: epoch
}
messagesRef.push(newMessage)
There are ways but weird, easiest way I can think of is push the message, and then grab the message to get the timestamp you just pushed.
Another way is get the key of a new pushRef
messagesRef.push().key
And then get timestamp from decoding the firebase key (since they are generated by timestamp)
decode firebasekey
#cartant state you can use server clock offset
var offsetRef = firebase.database().ref(".info/serverTimeOffset");
offsetRef.on("value", function(snap) {
var offset = snap.val();
var estimatedServerTimeMs = new Date().getTime() + offset;
});

Setting the milliseconds on Timeout based on given date time

I need help with setting my timeout for the function. I'm trying to set the timeout for a given date and time but my conversion of them to milliseconds is not working.
Here's my code. Please help.
<script>
var ref = firebase.database().ref().child("Message");
var newRef = ref.child("20161227125916539")
newRef.on('value',function(snap){
heading.innerText =snap.child("message").val();
});
ref.on("child_added",function(snap){
var date = snap.child("date").val();
var time = snap.child("time").val();
var type = snap.child("type").val();
var venue = snap.child("venue").val();
var route = snap.child("route").val();
var message = snap.child("message").val();
date = date + time;
date = date.getTime();
var now = new Date();
now = now.getTime();
set = date - now;
var explode = function(){
alert("Boom!");
};
setTimeout(explode, 2000);
});
</script>
You need to parse the date using new Date().
As you said, the value of date is "2016-12-27" and the value of time is "15:30", so while concatenating them, you also need an extra space. Something like:
date = date + " " + time;
var someDate = new Date(date);
var now = new Date();
var diffInMillis = now - someDate
var explode = function(){
alert ("Boom!");
}
setTimeout(explode, diffInMillis);
dateobj=new Date(datestring);
timeinmilliseconds=dateobj.getTime();
//by the way, may check the browsers console if sth is not working:
datestring.getTime();// error:undefined function
Youre calling the getTime function on a string. You need to convert it into a time obj first. Be aware of the right String format. There are good resources online.
The better Way:
A timeout is killed when the browser is reloaded. Thats bad. It would be better to store the time, and regularily check if the time is reached. That would survive reloads, crashes, shutdowns etc:
function set(timestring){
localStorage.setItem("timer",new Date(timestring).getTime());//store timer
check();//start checking
}
function check(){
if(var await=localStorage.getItem("timer")){//if timer is set
var now=new Date().getTime()
if(await<=now){//time reached, or reached in the past
alert("Yay, timer finished");
}else{//not reached yet
console.log(await-now+" left");//log the time left
setTimeout(check,1000);//check again in a scond
}}
window.onload=check;// browser started, check for an existing timer
Use like this:
set("28-12-2016 12:30");

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
A Timestamp is an object:
timestamp = {
nanoseconds: 0,
seconds: 1562524200
}
console.log(new Date(timestamp.seconds*1000))
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;
});
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
In fact, it only work to me when used
firebase.database.ServerValue.TIMESTAMP
With one 'database' more on namespace.
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
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.
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 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."
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;
}
Try this one,
var timestamp = firebase.firestore.FieldValue.serverTimestamp()
var timestamp2 = new Date(timestamp.toDate()).toUTCString()
Working with Firebase Firestone 18.0.1
(com.google.firebase.Timestamp)
val timestamp = (document.data["timestamp"] as Timestamp).toDate()
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()
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)
var date = new Date((1578316263249));//data[k].timestamp
console.log(date);
Iterating through this is the precise code that worked for me.
querySnapshot.docs.forEach((e) => {
var readableDate = e.data().date.toDate();
console.log(readableDate);
}
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()
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)
let jsDate = new Date(date.seconds * 1000 + date.nanoseconds / 1000000);
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.
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);
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.ServerValue.TIMESTAMP is the same as new Date().getTime().
Convert it:
var timestamp = '1452488445471';
var myDate = new Date(timestamp).getTime();

Convert UTC time to specific zone

I have the following data:
var currentTime: 2013-07-11 15:55:36+00:00
var currentTimezone: Africa/Asmera
I need a way to convert the currentTime in UTC to a new time based on currentTimezone.
I've looked into Timezone.js and I'm having trouble implementing it (the directions on the site are a little ambiguous)
The code for the function I'm intending on using is included. Thanks :)
<script>
$("#storeTime").click(function(){
storeCurrentTime();
})
$("#getTime").click(function(){
retrieveTime();
})
$("#storeTimezone").click(function(){
var yourTimezone = $('#timezone-select').find(":selected").text();
tz = yourTimezone.toString();
storeCurrentTimezone(tz);
})
$("#convertTime").click(function(){
//get the most recent UTC time, clean it up
var currentTime = $('#RetrievedTime').html();
currentTime = currentTime.split(": ")[1];
$('#convertedTime').html("Converted Time: " + currentTime);
//get the saved timezone
var currentTimezone = $('#storedTimezone').html();
})
</script>
You're going to need to know the timezone offset, so some sort of dictionary with strings to numbers.
// assuming your dictionary says 3 hours is the difference just for example.
var timezoneDiff = 3;
Then you can just make a new time like this
// Assuming you have the proper Date string format in your date field.
var currentDate = new Date(currentTime);
// Then just simply make a new date.
var newDate = new Date(currentDate.getTime() + 60 * 1000 * timezoneDiff);
Update
I've written a javascript helper for this which you can find at:
http://heuuuuth.com/projects/OlsonTZConverter.js
I pulled the timezone data from the wikipedia page https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
Usage is as follows once included the script.
var offset = OlsonTZConverter.GetUTCOffset("Africa/Asmera");
or if there is Daylight Savings in effect:
var offset = OlsonTZConverter.GetUTCOffset("Africa/Asmera",true);
These will throw if you pass an invalid timezone, but you can check if a timezone is valid with:
var isValid = OlsonTZConverter.Contains("Africa/Asmera");
or just look at the entire dictionary with:
var tzDict = OlsonTZConverter.ListAllTimezones();
Hope this maybe saves someone some time sometime :).

Categories