Snorlax Snorlax - 5 months ago 26
JSON Question

Angular Filter, compare JSON file date to today's date

<p id="appt_time" ng-if="x.dateTime | date: MM/dd/yyyy == {{todaysDate}}">SHOW ME IF TRUE{{todaysDate}} </p>


Plunkr:https://plnkr.co/edit/r2qtcU3vaYIq04c5TVKG?p=preview

x.dateTime | date: MM/dd/yyyy
gets a date and time which turns out to be when filtered:
06/18/2016
according to my json file.

What I'm trying to accomplish is to compare this "x.dateTime" to today's date and show the paragraph if the statement is true. So in my angular file, I have a
$scope.todaysDate = "06/18/2016"
, but the paragraph doesn't show.

HTML file:

<!DOCTYPE html>
<html>

<head>
<link rel="stylesheet" href="style.css">
<script src="https://code.angularjs.org/1.5.5/angular.js"></script>
<script src="script.js"></script>

</head>

<body ng-app="myApp" ng-controller="myCtrl">
<div ng-repeat="x in information">

<!--Compare Json Object to Javascript Object-->
<p ng-if ="x.dateTime">{{x.dateTime | date: MM/dd/yyyy }}</p>
<!--Compare Json Object to Today's Date-->
<p id="appt_time" ng-if="x.dateTime.valueOf() === todaysDate.valueOf()">Open in: {{todaysDate}} </p>
</div>
</body>

</html>


JS File:

// declare a module
var myAppModule = angular.module('myApp', []);
var todaysDate = new Date();


// configure the module.
// in this example we will create a greeting filter
myAppModule.controller('myCtrl', ['$scope','$http', function($scope, $http)
{

$scope.todaysDate = todaysDate;
$scope.test = "Volvo";

$http.get("time.json")
.then(function(data) {
$scope.information = data;
});
}]
);


JSOn file:

{
"dateTime":"2016-06-18T18:41:00.748-04:00"

}

Answer

Because you're dealing with dates and times, things can get tricky fast. I would suggest using the Moment.js library, as it makes this super easy:

ng-if="moment.utc(x.DateTime).isSame(todaysDate, 'day')"

The "day" there indicates how granular you want to compare the two values. However, it's relatively easy even without that library:

ng-if="x.DateTime.substring(0, 10) === todaysDate"

Where you change $scope.todaysDate to "2016-06-18".