Attempt to sort firebase database is not working - javascript

I am trying to sort firebase date by date but it is not working.
I have firebase data structure in this format
I use this function to call the node
var awardsref = CatalogueDB.ref("cageawards/" + mycagecode).orderByChild('Awarddate');
awardsref.on('value', Awardstable, errData);
this is the output
is there a work around to sort the data based on this date format?

As #GerardoHerrera pointed out, Firebase don't support sorting by Date. However, if you parse the dates and convert them to milliseconds based on the UNIX epoch, you should be able to sort them lexicographically according to that.
const date1 = new Date("04-07-2018").getTime();
date1; // 1523084400000
const date2 = new Date("06-02-2018").getTime();
date2; // 1527922800000
Since date1 is less than date2, it will sort as being before date2 in ascending order. Store those converted millisecond time values in your Firebase and you should be able to sort your dataset by them.
e.g.
"7MFD4" {
...
"SPE7L018P1428" {
"Awarddate": "04-07-2018",
"AwarddateMS": 1523084400000
...
}
...
}
Then do orderByChild('AwarddateMS').

According to the following page, How query data is ordered, a date is not considered in any sorting way. It first orders null values, then false values, then true, numbers, strings and finally objects.
And all sorting is made following a Lexicographical Order.
So you may need to do the sorting on the client side by your own methods.
ThereĀ“s another post where you can find an explanation on how to sort by date here

Related

Meteor.js / MongoDB between dates query not returning data

I have the following piece of code for getting results back from a Mongo Collection.
var currentDate = moment().toISOString();
// RETURNING: 2016-12-10T20:36:04.494Z
var futureDate = moment().add(10, "days").toISOString();
// RETURNING: 2016-12-20T20:36:04.495Z
return agenda = Agendas.find({
"agendaDate": { '$gte': currentDate, '$lte': futureDate }
});
And the date is stored in MongoDB Collection like below;
{
"_id" : ObjectId("584877e56466dd236cd95f15"),
"agendaDate" : ISODate("2016-12-12T17:28:25.000+0000"),
"agendaTime" : "20:59",
"agendaEvent" : "Test event"
}
However, I am not getting any results returning as all. I have set up 3 test documents, 2 in the range, 1 outside.
Can anyone explain what I'm doing wrong and help rectify the code?
You need to compare dates against actual date objects, not strings representing them.
That is, you need to get the date from your moment objects, using the toDate() method.
var futureDate = moment().add(10, "days").toDate();
Well actually moment.toISOString() returns a string, so you can't use it to compare with date object in your mongodb query.
You should consider creating a date object for that.
Regs,
Yann

D3: Format date type

I want to format a date in D3. Here is my code:
var format = d3.time.format("%Y/%m");
var dates = data.map(function(d){ return new Date("2016/01/03"); });
var formDate = format.parse(dates);
console.log(formDate);
My formDate seems to be null, don't know why.
In my chart the values are not displayed at all. How should I format it to get something like "2016/01" ?
Based on your comments, you need to use format as a function itself.
format.parse() is for parsing string representations of a date into a javascript Date (the opposite operation from what you are looking for).
For instance, given a date, 'd', you would use the following code to get what you would like:
var format = d3.time.format("%Y/%m");
var formattedDate = format(d);
Further adding to the confusion, it looks like you attempted to use parse() on a collection of dates. both parse() and format() only support individual strings/Dates respectively, so keep that in mind.
You haven't given enough information to suggest what structure your data is in, but the above should be enough to help you formulate a transform function for your x axis labels.

Comparing Dates with AngularJS

I am building an AngularJS/Rails web app, part of it is creating bookings (function bookings) and in the dashboard I am trying to display two different tabs one with Current Bookings and one with Previous Bookings. the booking model has a function_date attribute and I am retrieving it from the API into a $scope.bookings array.
How to I compare dates (run an if statement on it) to do if function_data > today's date store it into CurrentBookings array if not store it into PreviousBookings array?
Hope that makes sense.
P.S. I am still teaching myself how to program so it might be a stupid question for some.
many way solved this problem but i am using to convert time in milliseconds then easy to compare.
var n = Date.now();
its give the current
Return the number of milliseconds since 1970/01/01:
1460260009358
First, try converting your string into a date. Then compare it to now.
var date = new Date('2030-03-30'); //this is a Date object
if (date > new Date()) { //Date object comparison
//[...]
}
// or
if (date.getTime() > Date.now()) { //unix timestamp (integer) comparison
//[...]
}

How to sort an array of objects by date range and creation date?

I'm building a task list system, but for the life of me I can't figure out a way to sort an array of objects with a start and end date.
I want to default the task list by the task's creation date, and work on oldest tasks first.
I dont want to start a task until it is at least on the start date.
I want to complete a task a day before the end date.
Sorting the dates by start date is easy using underscorejs:
_.sortBy(arr, function(task) {
return task.start.dateTime;
})
But how do I take into context start date and end date, while still trying to keep it basely sorted by creation date?
Reading the doco provided by http://underscorejs.org/
sortBy says that it is a stable sort algorithm (meaning that it won't throw out the order on multiple sorts if the values are equal. See http://en.wikipedia.org/wiki/Sorting_algorithm) so you should be able to chain up sorting context safely:
var sortedArray = _(arr).chain()
.sortBy(function(task) {
return task.created.dateTime;
})
.sortBy(function(task) {
return task.start.dateTime;
})
.sortBy(function(task) {
return task.end.dateTime;
})
.value();
Have you tried that and can you provide some sample data to test with?

Issues with Date() when using JSON.stringify() and JSON.parse()

I am trying to calculate the difference between two times using JavaScript. It's just basic math but I seem to have some issues with that while using JSON.stringify() and JSON.parse().
If you're wondering why am I applying the JSON.stringify() function to the date, it's because I using local storage to store some data on the client side and use it whenever the client lands on my website again ( it's faster that way rather than making more requests to the server ). That data usually updates once in a while ( I'm grabbing the data through API from another website ), so I set up a data_update variable and I'm storing it together with the other data.
That way I'm grabbing the stored data from the local storage and check if the difference between data_update ( which is a date / time ) and the time / date when the check it's made and see if it's greater than a week / day /etc .
So that is the reason why I'm using the JSON functions. My problem is that when I'm parsing the data from the local storage, the date seems to be different from a Date() object.
I'm trying to do the next operation per say :
var x = JSON.parse(JSON.stringify(new Date()));
var y = JSON.parse(this.get_local_storage_data(this.data_cache_key)); // the data object stored on local storage
var q = y.data_update; // this is the variable where the Date() was stored
console.log(Math.floor((x-q)/1000));
The above will return null. Also when I want to see the Math.floor(x) result, it returns null again.
So what can I do in this situation ? Is there a fix for this ?
If you look at the output of JSON.stringify for a Date, you'll see that:
JSON.stringify(new Date())
Results in a string. JSON does not have a primitive representation of Date objects that JSON.parse will turn back into a Date object automatically.
The Date object's constructor can take a date string, so you can turn those string values back into dates by doing:
var x = new Date(JSON.parse(JSON.stringify(new Date())));
Then the arithmetic will work.
x = new Date(JSON.parse(JSON.stringify(new Date())))
y = new Date(JSON.parse(JSON.stringify(new Date())))
y - x
=> 982
JSON.stringify(new Date())
returns
"2013-10-06T15:32:18.605Z"
Thank God is: Date.prototype.toISOString()
As the recommended answer suggests, the date is simply converted to a string when using JSON.stringify.
Another approach that would maybe fit this use case is to store the time in milliseconds using Date.now():
// Date.now() instead of new Date()
const millis = Date.now();
console.log(millis);
// same output as input
console.log(JSON.parse(JSON.stringify(millis)));
That way you can be sure that what goes into JSON.stringify comes out the same when using JSON.parse.
This also makes it easy to compare dates, if you have two millisecond values, using < and >.
Plus you can convert the milliseconds to a date at any time (usually before you render it to the user):
const millis = Date.now();
console.log(millis);
console.log(new Date(millis));
NOTE: using milliseconds as your date representation is usually not recommended, at least not in your database: https://stackoverflow.com/a/48974248/10551293.

Categories

Resources