Shailendra Madda
Shailendra Madda

Reputation: 21551

Angular JS compare two Dates are equal or not

I have used this angular code to compare two dates are equal or not.

Code:

<div class="batchPlannings">
  <div ng-repeat="batchPlanning in batchPlannings"
    ng-animate="'animate'">
    <div ng-switch="batchPlanning.status">
      <div ng-switch-when="MAPPED" class="my-switch-animation">
        <p>start date: {{batchPlanning.startDate}}</p>
        <p>placement date: {{placementDate}}</p>
        <div ng-if="batchPlanning.startDate === {{placementDate}}"
          class="my-switch-animation">
          <a th:href="@{/placement}" class="list-group-item"
            sec:authorize="hasAnyRole('ROLE_SYSTEM_ADMIN', 'ROLE_CENTER_ADMIN')">Batch
            with batch code '{{batchPlanning.batchCode}}' is ready for
            placements</a>

        </div>
      </div>
    </div>
  </div>
</div>

Here I wanna check test those two dates or equal or not I am getting those dates perfect and fine and those are also equal but unable to make that condition as true. I checked it with == as well but no result.

Any help or suggestion will be appreciated.

Upvotes: 1

Views: 15382

Answers (1)

Reactgular
Reactgular

Reputation: 54771

JavaScript uses objects to store date values. When you want to compare if two dates are equal don't do this date1 === date2. That will just tell you if the two variables reference the same object.

To check if two dates are equal use the getTime() method of the date object. Like this:

date1.getTime() == date2.getTime()

Be careful because any difference in seconds will fail to match the dates.

Now ng-if will accept AngularJS expressions. You have this in your example batchPlanning.startDate === {{placementDate}}. Which is an invalid expression. {{placementDate}} is syntax used to create a binding.

What you want to do is batchPlanning.startDate.getTime() == placementDate.getTime().

Ensure that both variables are valid JavaScript date objects.

I recommend that you use the moment javascript library for date processing. It makes working with dates a lot easier.

http://momentjs.com/

Upvotes: 6

Related Questions