Is there a way to display current data in angularJS based on the current time?

My database contains timestamps like 2016-12-30 00:30:10 which I retrieve using the $http module in Angular. Below is a snippet of my Angular code:

    angular
        .module('sampleApp')
        .controller('ReportCtrl', ReportCtrl)
        .factory('Reports', Reports)
        .filter('dateToISO', dateToISO);

    function ReportCtrl($scope, Reports) {
        $scope.returns = [];
        $scope.loadReturns = function () {
            Reports.getReturns().then(function (response) {
                $scope.returns = response.data;
            }, function (error) {
                console.log(error);
            })
        }
    }

function dateToISO() {
        return function (input) {
            input = new Date(input).toISOString();
            return input;
        };
    }

In the HTML:

        <tr ng-repeat="r in returns | orderBy:'-phdate'">
            <td ng-bind="r.product_name"></td>
            <td ng-bind="r.quantity"></td>
            <td ng-bind="r.username"></td>
            <td ng-bind="r.phdate | dateToISO | date:'medium'"></td>
        </tr>

The current output looks like this:

Now, I want to display only the data with today's date, for example, if today is 12/30/2016. Should I handle this logic on the server-side or can it be done within Angular? Any assistance would be greatly appreciated.

Answer №1

If you want to achieve this using angular, follow the steps below:

HTML

    <tr ng-repeat="r in returns | orderBy:'-phdate'">
        <td ng-bind="r.product_name"></td>
        <td ng-bind="r.quantity"></td>
        <td ng-bind="r.username"></td>
        <td ng-bind="compareDate(r.phdate)"></td>
    </tr>

Javascript

    var compareDate = function (phdate) {
         // Initialize time to zero
         var curDate = new Date();
         curDate.setHours(0);
         curDate.setMinutes(0);
         curDate.setSeconds(0);

         var pDate = new Date(phdate);
         pDate.setHours(0);
         pDate.setMinutes(0);
         pDate.setSeconds(0);

         if (curDate === pDate) {
             return $filter('date')(pDate, 'medium');
         }
    }

Answer №2

    $scope.checkDate = function(checkdate){
        var dateObject = new Date();
        var monthNow = dateObject.getUTCMonth() + 1;
        var dayNow = dateObject.getUTCDate();
        var yearNow = dateObject.getUTCFullYear();
        var currentDateCheck = dayNow + "" + monthNow + "" + yearNow;

        var dateObjectToCheck = new Date(checkdate);
        var monthChecked = dateObjectToCheck.getUTCMonth() + 1;
        var dayChecked = dateObjectToCheck.getUTCDate();
        var yearChecked = dateObjectToCheck.getUTCFullYear();
        var checkedDate = dayChecked + "" + monthChecked + "" + yearChecked;

        if(currentDateCheck == checkedDate){
            return true;
        } else {
            return false;
        }
    }



<tr ng-repeat="r in returns | orderBy:'-checkdate'" ng-if="checkDate(r.checkdate)">
    <td ng-bind="r.item_name"></td>
    <td ng-bind="r.amount"></td>
    <td ng-bind="r.user"></td>
    <td ng-bind="r.checkdate"></td>
</tr>

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

Executing a complex xpath using Java Script Executor in Selenium WebDriver

When working with a large grid and trying to find an element using XPath, I encountered some difficulties. The XPath used was: By.xpath("//div[contains(text(),'" +EnteredCompetitionName+ "')]/preceding- sibling::div[contains(concat(' &apo ...

Learn how to call JavaScript code from an HTML file using Ajax

I am encountering an issue with my website. The index.html page contains JavaScript code that triggers an AJAX request to show the content of other.html inside a div in index.html. However, despite the other.html loading correctly, the JavaScript code wit ...

Issue with the _.filter function in lodash library when used in a Node.js environment

My goal is to remove rows from a CSV file that already contain email addresses found in Mailchimp. Although I attempted to achieve this with a function, it seems that the number of elements returned is not accurate: async function testDeleteEmails(listID, ...

Incorporate a fontawesome icon into a dynamically created button using ajax

Is it possible to insert fontawesome icons into a button created using this code snippet? $.each(response, function (i, item) { trHTML += '<tr><td>' + item.name + '</td><td>' + "<input type='button&apo ...

Exiting callback function in JavaScript

Is there a way to retrieve the return value from within a node.js/javascript callback function? function get_logs(){ User_Log.findOne({userId:req.user._id}, function(err, userlogs){ if(err) throw err; if(userlogs){ ...

"Utilizing regular expressions in JavaScript to check for multiple

I have a function that replaces HTML entities for & to avoid replacing &amp; but it still changes other entities like &, ", >, and <. How can I modify the regex in my function to exclude these specific entities? &apos; &quo ...

``How can I extract the last string in Vue.js when working with string processing?

I've been working with strings in vuejs and currently have 4 URL strings: https://web-sand.com/product/slug/apple-iphone-13 https://web-sand.com/product/slug/samsung-galaxy https://web-sand.com/product/slug/xiaomi-red https://web-sand.com/product/slug ...

How can I dive into a nested array to access the properties of an object within?

My array, called sportPromise, is structured like this: 0: Array[0] 1: Array[1] 2: Array[2] 3: Array[3] When I run console.log(angular.toJson($scope.sportPromise, 'pretty'));, the output looks like this: [ [], [ { "id": 5932, ...

Angular login/signup modal/dialog component for seamless user authentication

Currently, I am working on adding a login/signin dialog to my app similar to the one used by Medium. After doing extensive research online, I have decided to use the $modal from angular ui-bootstrap for this. Can anyone please recommend a tutorial that wil ...

Is there a way to circumvent the mouse up event?

I want to create a feature where when a user clicks down, something specific occurs. The sequence of events includes: An action taking place (which is not the focus here). Triggering a mouse up event. Implemented with: angular, html, css. Excludes: jQue ...

Ways to avoid storing repeating paragraphs in JavaScript Array?

Can someone help me with my code? I am struggling to prevent duplicate data from being saved into an array. When I click on any two paragraph elements, the text inside them gets added to an array named `test`. However, I want to avoid saving the same tex ...

Encountering an issue while attempting to replicate the Spotify app on localhost:3000. The error message "TYPEERROR: Cannot read property 'url' of undefined" is hind

As a first-time user of stackoverflow, I am unfamiliar with its rules and regulations, so I apologize in advance for any mistakes I may make. Currently, I am attempting to create a Spotify clone using React. Everything was going smoothly until I completed ...

Tips for extracting data from a JQuery table with Python

My goal is to extract information from the top ten items on a manga website using Python Selenium/BeautifulSoup. However, I am facing challenges due to the website loading its content through a jquery script. The tutorials and guides I have followed do not ...

Unable to use model.find() in post findOneAndUpdate hook for Mongoose

Introduction In Mongoose, I am facing an issue with a post findOneAndUpdate hook where I need to perform a database query. Specifically, when trying to execute a .find() operation on another model, I encounter the following error: Error Description Typ ...

Is there a way to retrieve the chosen row or a group of rows in ng-grid?

Is there a method to retrieve the selected row or all rows in the grid, including those that are not visible on the screen? I am looking for a way to access the ngRow objects specifically, rather than just the items they represent, so that I can pinpoint ...

Having trouble retrieving the ID of the clicked element in AngularJS?

I have successfully implemented a function in angularjs to retrieve the id of the clicked element. Below is my code snippet html <a href="#faqinner/contactform" class="clearfix" ng-click="getCateId($event)" id="{{option.id}}"> <span class= ...

What is the best way to transform an array of objects into an array that contains a distinct identifier in JavaScript?

I am currently working with an array of objects structured like this: { "data": [ { "id": 1, "from": "2022-08-01", "to": "2022-08-05", & ...

Update the content of the widget

Currently, I am utilizing the following script to display NBA standings: <script type="text/javascript" src="https://widgets.sports-reference.com/wg.fcgi?script=bbr_standings&amp;params=bbr_standings_conf:E,bbr_standings_css:1&amp"></sc ...

Exploring the Magic of Class Variable Destructuring in React

Is there a simpler method to break down a prop object and assign them to variables of the same name in the class? I am familiar with ({ first: this.first, second: this.second, } = props) however, it can get complicated when dealing with numerous variable ...

Discovering the country associated with a country code using ngx-intl-tel-input

In my application, I am trying to implement a phone number field using this StackBlitz link. However, I have observed that it is not possible to search for a country by typing the country code (e.g., +231) in the country search dropdown. When I type a coun ...