Using ng-if to compare dates in AngularJS without considering the year

I am facing a comparison issue with dates in my code. I have one date that is hardcoded as the first day of the month, and another date coming from the database (stored in a JSON object). When I compare these dates using ng-if, it seems to ignore the year and only compares the date and month.

Below is the relevant part of my code:

  <tr ng-repeat="c in listBCust | orderBy : orderByField | filter : srchInv" ng-class="{'holdCust':'01/09/2015'>(c.startDate.slice(6,-2) | date:'dd/MM/yyyy')}">

    <td>  
       <div ng-if="'01/09/2015'>(c.startDate.slice(6,-2) | date:'dd/MM/yyyy')" style="background-color:#E25D5D">{{c.startDate.slice(6,-2) | date:'dd/MM/yyyy'}}</div>

       <div ng-if="'01/09/2015'<(c.startDate.slice(6,-2) | date:'dd/MM/yyyy')" style="background-color:#E25D5D">{{c.startDate.slice(6,-2) | date:'dd/MM/yyyy'}}</div>
       <div>{{MfstDate}}</div>
    </td>

  </tr>

Answer №1

You can easily modify the date format to yyyy/MM/dd and everything should work smoothly.

// Custom code block

angular.module("app",[]).controller('ctrl',function($scope){
  $scope.startDate = '/Date(1441045800000)/';
  $scope.mfstDate = new Date(2015,8,1);
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
    <h1>Hello Plunker!</h1>
    {{startDate.slice(6,-2) | date:'dd/MM/yyyy'}}
    <div ng-if="(mfstDate| date:'yyyy/MM/dd')>(startDate.slice(6,-2) | date:'yyyy/MM/dd')" style="background-color:#E25D5D">{{startDate.slice(6,-2) | date:'dd/MM/yyyy'}} less {{mfstDate| date:'dd/MM/yyyy'}}</div>
    <div ng-if="(mfstDate| date:'yyyy/MM/dd')<(startDate.slice(6,-2) | date:'yyyy/MM/dd')" style="background-color:#E25D5D">{{startDate.slice(6,-2) | date:'dd/MM/yyyy'}} greater {{mfstDate| date:'dd/MM/yyyy'}}</div>
  </div>

UPDATE it appears that you just need to make a small adjustment in your getFirst_Last_DateOfMonth function. There is no need to manually format the string since Angular provides a useful filter called date which you are already using within the view.

Simply return the date instead of a string,

function getFirst_Last_DateOfMonth(F_L) {
    //here F=First Date of Current month
    //     L=Last Date of Current Month

    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth();

    var yyyy = today.getFullYear();

    var firstLastDay = F_L == 'F'? new Date(yyyy,mm,1) : new Date(yyyy, mm + 1, 0);
    return firstLastDay; //return Date object and in view use date filter when need comaring
    //return $filter('date')(firstLastDay,'yyyy/MM/dd'); //uncomment if want return formatted string
}

Check out the updated snippet below

// Modified code block

angular.module("app", []).controller('ctrl', function($scope, $filter) {
  function getFirst_Last_DateOfMonth(F_L, formatString) {
    //here F=First Date of Current month
    //     L=Last Date of Current Month

    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth();

    var yyyy = today.getFullYear();

    var firstLastDay = F_L == 'F' ? new Date(yyyy, mm, 1) : new Date(yyyy, mm + 1, 0);
    return !formatString ? firstLastDay //return Date object and in view use date filter when need comaring
      : $filter('date')(firstLastDay, 'yyyy/MM/dd'); //uncomment if want return formatted string
  }

  $scope.startDate = '/Date(1441045800000)/';
  $scope.mfstDate = getFirst_Last_DateOfMonth('F');

  $scope.mfstDateString = getFirst_Last_DateOfMonth('F', true);
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <h1>Hello Plunker!</h1>
  {{startDate.slice(6,-2) | date:'dd/MM/yyyy'}}
  <div>
    mfstDate is date!
    <div ng-if="(mfstDate| date:'yyyy/MM/dd')>(startDate.slice(6,-2) | date:'yyyy/MM/dd')" style="background-color:#E25D5D">{{startDate.slice(6,-2) | date:'dd/MM/yyyy'}} less {{mfstDate| date:'dd/MM/yyyy'}}</div>
    <div ng-if="(mfstDate| date:'yyyy/MM/dd')<(startDate.slice(6,-2) | date:'yyyy/MM/dd')" style="background-color:#E25D5D">{{startDate.slice(6,-2) | date:'dd/MM/yyyy'}} greater {{mfstDate| date:'dd/MM/yyyy'}}</div>
  </div>
  <div>
    mfstDate is formatted string!
    <div ng-if="mfstDateString>(startDate.slice(6,-2) | date:'yyyy/MM/dd')" style="background-color:#E25D5D">{{startDate.slice(6,-2) | date:'dd/MM/yyyy'}} less {{mfstDateString}}</div>
    <div ng-if="mfstDateString<(startDate.slice(6,-2) | date:'yyyy/MM/dd')" style="background-color:#B8BCEF">{{startDate.slice(6,-2) | date:'dd/MM/yyyy'}} greater {{mfstDateString}}</div>
  </div>
</div>

Answer №2

To optimize your code, I recommend creating a function within your controller to handle the date comparison. This function can then be called within your ng-if statement for efficient comparison of dates. Utilizing the Date object is crucial for accurate date comparisons.

Here's how you can implement this:

<div ng-if="compareDates(date1, date2)">*content*</div>

The function should resemble something like this:

function compareDates(date1, date2) {
   var dateObj1 = new Date(date1);
   var dateObj2 = new Date(date2);

   return (dateObj1 > dateObj2);
}

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

Exploring PHP cURL with the power of jQuery

function php_download($Url){ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $Url); curl_setopt($ch, CURLOPT_REFERER, "http://www.example.org/yay.htm"); curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0"); curl_setopt($ch, CURLOPT_H ...

I am experiencing difficulty with loading the local images stored in the /public/images directory of my React app

I am currently working on a component called Portafolio.js where I am utilizing the map function to retrieve each object from a file named "trabajos.js" that contains all the objects with their respective properties. My goal is to display an image for each ...

unable to log out firebase user

Currently, I am attempting to sign out the user who is already signed in within my Angular app. Here is my client service code: export class AuthClientService { public register(email: string, password: string): Observable<Object> { retu ...

Guide to parsing and storing a JSON file in Node.js using AngularJS's $http.post functionality

EXCUSE THE POOR ENGLISH I am encountering an issue with capturing a JSON sent using $http.post from an angularjs to a nodejs with express (I have to send it because I cannot save a file on the server's client-side) The following is my code in angula ...

Updating parameter value upon the execution of an internal function in Javascript

How can I log the text from a textbox to the console when a button is clicked in this code snippet? <body> <input type="text" id="ttb_text" /> <script type="text/javascript"> function AppendButton() { var _text = ''; ...

Accessing Wikipedia's API in order to retrieve search query results

I'm currently working on incorporating Wikipedia's API into my web page to execute a search query and display the results. Here is the progress I've made so far: "use strict"; $(document).ready(function(){ function searchWikipedia(searchC ...

Rendering props conditionally in React

I am currently facing an issue with two different states retrieved from API calls: 'movieList' and 'search'. Both of them contain arrays of movies. The 'movieList' state is automatically rendered on the page to display popular ...

Counter is effective for the initial post, yet it does not function properly for the subsequent post

Can anyone help with an issue I'm having with my JavaScript counter? It works for the first comment, but not the second one. This problem persists whether I use PHP or JavaScript. Below is the JavaScript code for the counter: var count = (function() ...

Creating a JavaScript object and retrieving the values of numerous input fields with identical classes

I have encountered an issue that I need assistance with: <input title="1" type="text" class="email"> <input title="2" type="text" class="email"> <input title="3" type="text" class="email"> The HTML code above shows my attempt to extract ...

An odd issue has arisen where the website functions properly in Firefox 3.0 but encounters problems when accessed in Firefox 3

Could someone investigate this issue for me? When you click on the showcase and then on the logo, a modal window should open with the logo. It works perfectly in FF 3.0, but in FF 3.5, the tab switches from showcase to home after clicking the logo. Even ...

Before beginning my selenium scripts, I need to figure out how to set an item using Ruby in the browser's localStorage

Before running my selenium scripts, I am attempting to store an item in the browser's localStorage. I attempted to clear the local storage using this command: driver.get('javascript:localStorage.clear();') This successfully cleared the lo ...

PHP question about maintaining data continuously

So, I've created this interesting JavaScript 'thing' with the help of jQuery and AJAX. The main concept behind it is that a div can be edited (contenteditable=true), which sparked the idea to develop a chatroom-like feature. It's pretty ...

retrieving an array of checkbox values using AngularJS

As a beginner in Angular, I have been struggling to implement a feature where I can add a new income with tags. I have looked at similar questions posted by others but I still can't get it to work. The tags that I need to use are retrieved from a ser ...

Error in Browserify Express App: Unexpected token while parsing the file

I have been attempting to browserify a javascript file. When I run the command: browserify global.js -o bundle.js An error message is returned: Error: Parsing file C:\ocquiz\public\javascripts\global.js: Unexpected token (756 ...

Identifying Cross-Origin (CORS) Error from Other Errors in JavaScript's XMLHttpRequest()

I am currently working on detecting when an XMLHttpRequest() fails due to a Cross Origin Error rather than a bad request. Take, for example: ajaxObj=new XMLHttpRequest() ajaxObj.open("GET", url, true); ajaxObj.send(null); Let's consider ...

Conflicting Transformation Properties Causing CSS Issues Within a Single Element

I'm currently working on a user interface where users can drag and drop a box with a red outline to position it on the screen within a black box. See the UI here Alternatively, users can also move the box by adjusting the inputs on the right side. ...

Ensuring secure communication with PHP web service functions using Ajax jQuery, implementing authentication measures

jQuery.ajax({ type: "POST", url: 'your_custom_address.php', dataType: 'json', data: {functionname: 'subtract', arguments: [3, 2]}, success: function (obj, textstatus) { if( !('error' in obj) ) { ...

Add characters to div using JavaScript

I am curious about which framework, if any, would be most effective for capturing keystrokes and adding them to an HTML element such as a "p" element. My goal is to allow the client to type something on the keyboard and have it immediately displayed in the ...

How can you tell if a specific keyboard key is being pressed along with the CTRL button?

Is there a way to call functions when a specific key is pressed along with the CTRL key (on a Windows system)? While testing for a particular keyCode, I used event.keyCode. I researched the codes assigned to each key and assumed that 17 + 73 would represe ...

Property computation being initiated before property initialization

I am encountering an issue in my Vue application where I am trying to filter an array received from map getters based on a type prop within a computed property. Despite verifying that both the array elements and the prop are strings, the filtering process ...