Eric Mitjans Eric Mitjans - 1 year ago 74
Javascript Question

Querying MomentJS dates on IndexedDB & AngularJS - Dates vs Strings

So, I just had a big "Oh Snap!" moment.

I'm using MomentJS with AngularJS and IndexedDB in an offline app.

All my records are stored with an index

based on the date property of the object.

The problem comes when I try to run queries based on the date using the following code:

$scope.redoresults = function(){
$indexedDB.openStore('records', function(store){
$scope.upper = moment($scope.dates.endDate).format("DD[/]MM[/]YYYY");
$scope.downer = moment($scope.dates.startDate).format("DD[/]MM[/]YYYY");

var find = store.query();
find = find.$between($scope.downer, $scope.upper, false, false);
find = find.$index("date_idx");
$scope.daterange = e;

The query was delivering weird results, sometimes correct, sometimes not.
Until I realized that I'm actually querying against strings, not dates.
Being so, a query between 01/08/2016 and 31/08/2016, will still deliver me results containing 20/09/2016, because as a number it's indeed between the range.

I feel I'm missing something structure-wise.

Any comment on how to solve this issue?

Should I query against some other index? But then how can I compare the dates?

Answer Source
  • Store dates as dates, and query using dates.
  • Or, store dates as timestamps (e.g. date.getTime()), and then query using timestamps
  • Do not store dates as dates and then query with a string date, this will produce junk.
  • Do not store dates as strings, and then query with a string date, this will produce junk. String values are compared lexicographically which can easily depart from how dates are compared.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download