Utilizing Angular Filter to compare the date in a JSON file with the current system date

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

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

x.dateTime | date: MM/dd/yyyy retrieves a date and time which results in being filtered as: 06/18/2016 as per my json file.

My goal is to compare this "x.dateTime" with today's date and display the paragraph if the condition holds true. Hence, in my angular file, I set $scope.todaysDate = "06/18/2016", but the paragraph does not appear.

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 on: {{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 №1

Working with dates and times can be quite challenging. I recommend utilizing the Moment.js library for a more straightforward solution:

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

The use of "day" specifies the level of detail in comparing the two values. Alternatively, you can achieve similar results without relying on an external library:

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

Simply update $scope.todaysDate to "2016-06-18".

Answer №2

To determine if a date is today, create a validate function that will return true. Remember to include $filter as well.

$scope.validate = function(date) {
   return $filter('date')(date, 'your format') === $filter('date')(new Date(), 'your format');
}

In the HTML code:

<p id="appt_time" ng-if="validate(x.dateTime)">SHOW ME IF TRUE{{x.dateTime}} </p>

Answer №3

Check out this link:

https://plnkr.co/edit/ZLJB5i1nQu9RYUV5FAX3?p=preview

// time.json

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

}]

//script.js

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

Your issue has been resolved

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Customizing URLs in AngularJS using ui-router allows for more personalized

Hey there, I've encountered an issue with my app. Users can sign up as merchants and have their own store name with a URL structure like this: http://localhost:8000/#/storename The problem arises when the default homepage subpages, such as contactus ...

How do I go about updating my code for welcome messages from discord.js v12 to v13?

While watching a YouTube tutorial on welcome messages, I decided to copy the entire code. However, when I tried using this code with discord.js v13, it didn't work. Strangely enough, everything seemed to function perfectly fine with discord.js v12. In ...

Looking to retrieve the specific clientX and clientY JavaScript Position within a child div element on a Wordpress Page?

I've implemented a highlight hover map in JavaScript that displays an 'info box' div when hovering over a specific area at . However, I'm encountering an issue where the 'info box' doesn't appear precisely at the mouse lo ...

Could converting a 47-byte JSON string into 340 MB be possible through JSON stringification?

var keys = [7925181,"68113227"]; var vals = {"7925181":["68113227"],"68113227":["7925181"]}; var temp = []; for (var i = 0; i < keys.length; i++) { temp[keys[i]] = vals[keys[i]]; } //alert(JSON.stringify(vals).length); alert(JSON.stringify(temp).le ...

Creating a custom function in JavaScript to interact with the `windows.external` object specifically for use

In my current project, I am facing an issue with JavaScript file compatibility across different browsers. Specifically, I have a JavaScript file that calls an external function (from a separate file) using windows.external, like this: windows.external.se ...

Tips for extracting the chosen text during a 'change' event

I need to access the text of the currently selected object. When I use $(this).text(), I end up getting all available selections I have attempted the following methods without achieving the desired result: $(this).text() $(this).selected() $(this).se ...

Having trouble populating and submitting a selected option from a dropdown menu in Angular?

Upon loading the page, the Category dropdown automatically populates with data from the database. However, when I attempt to select a value from the dropdown and click a button to post the data to a specified URL, an error occurs: ERROR Error: Error tryin ...

Leveraging jQuery's $.getJSON method to fetch localization data from aprs.fi

Utilizing JSON to retrieve localization coordinates from is my current goal. I came across an example on http://api.jquery.com/jQuery.getJSON: <script> $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", { tags: ...

Unable to specify the content-type as 'application/json' using jQuery.ajax

When I use the following code $.ajax({ type: 'POST', //contentType: "application/json", url: 'http://localhost:16329/Hello', data: { name: 'norm' }, dataType: 'json' }); In Fiddler, I can see th ...

Template for developing projects using JavaScript, HTML5, and CSS3 in Visual Studio 2013

After recently downloading Visual Studio 2013 Express for Web, I am struggling to figure out how to deploy projects that only consist of JavaScript, HTML5, and CSS3. Despite searching online for JavaScript templates and even trying to download Visual Stu ...

How can you utilize a computed property in a Vue component to select all the text within it?

When using $event.target.select(), I usually can select all the text. However, in this scenario, it seems to be selecting everything and then replacing the selection with the computed property. How can I select all after the computed property has finished? ...

Using TypeScript generics with the `keyof` operator may result in rejection

I created a custom method using the RXJS library which looks like this : function Subject<T>(t: T):T { return t; } In addition, I defined an interface that specifies the structure of my application values. Additional keys can be added to this i ...

How can I access the value of one method within the same class and use it in another method in Ionic?

I encountered an error while trying to utilize data from my API call in IONIC's home.ts file for the google map method also located in home.ts. Unfortunately, this resulted in a null or undefined error. Is there a way to effectively use data from one ...

Is it possible to specify the database connection to use in npm by setting an environment variable?

I have established a database connection in a JavaScript file. const dbCredentials = { user: 'something', host: 'localhost', database: 'something', password: 'something', port: 1111, }; export default d ...

Firebase onCall function is executing properly, however, it is only delivering {data: null} as the

I am facing an issue with my cloud function where everything runs smoothly until I attempt to return a response back to the front-end. Despite successfully modifying databases, the final log points D and G still show {data:null} as the output. I have a fe ...

Building a promotional widget

I'm currently working on developing an ad widget that can be easily reused. I'm debating whether to use jQuery or stick with pure JavaScript for this project. What are your thoughts on the best approach for creating a versatile and efficient ad w ...

Is there a way to transform a personalized jquery event listener into an angularjs listener?

A custom event listener was created using jQuery for an angularjs component. The event is triggered by a non-angularjs library. $( "#myDiv" ).on( "CornerstoneImageRendered", function(e) { // buisness logic }); The element myDiv is a div that belongs t ...

Encountering an issue with html2canvas: receiving an error message stating "object

To print the div using Javascript, I encountered an issue with the generated barcode not appearing in the printed page. This led me to use the html2canvas approach to 'render' the div before printing it out. Here is the code snippet: HTML: < ...

Guide to sending an Array of objects in the request body using RestAssured in Java

Here is the Request I am working with: [ { "userId": "value1" },{ "userId": "value2" } ] I attempted to create a POJO class and construct the request, as well as using an ArrayList, but there ...