I have found a little Javascript function that compares dates and returns true when a certain date is within the range of two other dates. It's working fine mostly, but for some reason it returns false when the compared date is equal to the end date. It works with the start date though, that's why it's confusing me. Anyone see what I'm missing?
var dates = {
convert:function(d) {
// Converts the date in d to a date-object.
return (
d.constructor === Date ? d :
d.constructor === Array ? new Date(d[0],d[1],d[2]) :
d.constructor === Number ? new Date(d) :
d.constructor === String ? new Date(d) :
typeof d === "object" ? new Date(d.year,d.month,d.date) :
NaN
);
},
inRange:function(d,start,end) {
// Checks if date in d is between dates in start and end.
return (
isFinite(d=this.convert(d).valueOf()) &&
isFinite(start=this.convert(start).valueOf()) &&
isFinite(end=this.convert(end).valueOf()) ?
start <= d && d <= end :
NaN
);
}
}
edit: Here are my inputs: I get my test data from a database, this is the output
http://zoiglapp.bplaced.net/data/selectAll.php
(sorry it doesn't look very pretty, but the important fields are zoiglBegin and zoiglEnd). As you can see, I have one timerange that ends on 2015-11-09 and one that starts there. The latter one is showing fine, the former one isn't showing up.
This is my AngularJS Controller with the database data, the today variable and the compare function I found:
app.controller('HomeController', ['$scope', '$http', function($scope, $http) {
$scope.today = new Date();
$http.get("data/selectAll.php")
.success(function(data) {
$scope.lokale = data;
});
$http.get("data/selectCities.php")
.success(function(data) {
$scope.cities = data;
});
$scope.dates = {
convert:function(d) {
// Converts the date in d to a date-object.
return (
d.constructor === Date ? d :
d.constructor === Array ? new Date(d[0],d[1],d[2]) :
d.constructor === Number ? new Date(d) :
d.constructor === String ? new Date(d) :
typeof d === "object" ? new Date(d.year,d.month,d.date) :
NaN
);
},
inRange:function(d,start,end) {
// Checks if date in d is between dates in start and end.
return (
isFinite(d=this.convert(d).valueOf()) &&
isFinite(start=this.convert(start).valueOf()) &&
isFinite(end=this.convert(end).valueOf()) ?
start <= d && d <= end :
NaN
);
}
};
}]);
and here is where I call the function in the ngIf directive:
<div ng-repeat="city in cities | orderBy:'city'">
<h2>{{city.city}}</h2>
<accordion close-others="true">
<accordion-group heading="{{lokal.name}}" ng-repeat="lokal in lokale | filter:city.city | orderBy:'name'" ng-if="dates.inRange(today, lokal.zoiglBegin, lokal.zoiglEnd)">
[...]
</div>
s = new Date(2015,1,1); e = new Date(2015,12,31); dates.inRange(Date(2015,1,1),s,e); dates.inRange(Date(2015,12,31),s,e);both returned true... so not sure what your problem is - Simon Hänisch