8

I am fairly new to angularjs, but here it goes. I am able two dates through angularjs in the form dd/mm/yyyy, but what I need to do is somehow subtract the two dates to get the difference in days between the two. I created a jquery function to do this, but I don't know how to pass in the two dates to the function. So I was wondering if there was a different way to go about this?

I am trying to set up a trigger system depending on the number of days in between the two dates for certain things to be stylized. For example if it's within 10 days I want it to use style 1 and if its within 20 days use style 2 and so on.

2
  • What does your code look like? Commented Mar 8, 2013 at 16:27
  • Any thoughts on the 2 answers added? Commented Mar 15, 2013 at 14:44

8 Answers 8

14

Basic javascript way:

var d1 = new Date('01/16/2013');
var d2 = new Date('02/26/2013');
var milliseconds = d2-d1;
var seconds = milliseconds / 1000;
var minutes = seconds / 60;
var hours = minutes / 60;
var days = hours / 24;

Using one of the Date libraries (such as moment.js):

var d1 = moment("01/16/2013");
var d2 = moment("02/26/2013");
var days = moment.duration(d2.diff(d1)).asDays();
Sign up to request clarification or add additional context in comments.

Comments

5

you simply convert date into timestamp and then subtract.

var Date1 = 08/16/2004;
var Date2= 10/24/2005;

var timestamp1 = new Date(Date1).getTime();
var timestamp2 = new Date(Date2).getTime();

var diff = timestamp1 - timestamp2


var newDate = new Date (diff);

Comments

4

You can use angular-moment to calculate the difference, using the amDifference filter:

Get the difference between two dates in milliseconds. Parameters are date, units and usePrecision. Date defaults to current date. Example:

<span>Difference: {{ dateFrom | amDifference : dateTo : 'days' }} days</span>

Comments

2

I'm also an angularjs novice but wouldn't you handle this by making properties available through your javascript view model?

For example have a style field that changes based on the date fields (ie style returns style 1 when if the difference is 10 days) and hopefully through the angularjs binding the updates will propagate to the screen.

I think the right term for this is a computed property or calculated property

EDIT

Not sure if this is what you're looking for but see fiddle for example of calculating date diff and changing a style all based off properties of the view model (scope)

scope.diff and scope.col are the 2 properties to bind to

http://jsfiddle.net/chrismoutray/wfjv6/

HTML

<script src="http://code.angularjs.org/0.10.4/angular-0.10.4.min.js" ng:autobind></script>
<div ng:controller="ComputedPropertiesCtrl">
    first date <input ng:model="firstdate"> second date <input ng:model="seconddate"> difference {{diff}}
    <div>when the difference is greater than 10 color changes to green</div>
    <div>eg set the second date to 15/01/2013</div>
    <div style="background-color:{{col}};"> State </div>
</div>

JS

function ComputedPropertiesCtrl() {
    var scope = this;
    scope.firstdate = '01/01/2013';
    scope.seconddate = '10/01/2013';
    scope.data_before = [];
    scope.differenceInDays = function() {

        var dt1 = scope.firstdate.split('/'),
            dt2 = scope.seconddate.split('/'),
            one = new Date(dt1[2], dt1[1]-1, dt1[0]),
            two = new Date(dt2[2], dt2[1]-1, dt2[0]);

        var millisecondsPerDay = 1000 * 60 * 60 * 24;
        var millisBetween = two.getTime() - one.getTime();
        var days = millisBetween / millisecondsPerDay;

        return Math.floor(days);      
    };
    scope.color = function() {
        return (scope.differenceInDays() > 10) ? 'green' : 'red';
    };

    scope.$watch('[firstdate, seconddate]', function(currScope,newVal,oldVal) {
        scope.data_before = oldVal;
        scope.diff = scope.differenceInDays();
    });

    scope.$watch('[firstdate, seconddate]', function(currScope,newVal,oldVal) {
        scope.data_before = oldVal;
        scope.col = scope.color();
    });
}

CSS

h2 { position: fixed; right: 10px; top: 10px; color: red; background:white;z-index:1000; }
input { width: 100px; }
div { margin: 10px; padding: 10px; }

5 Comments

well i guess the real problem is how do i calculate the different in days?
@ChrisMoutray that is great example but how to do it for each item in array ?
@vittore do you mean that you've got a list of objects like the TODO example on angularjs sites main page? In which case I think each child object would have to be a scope object var newscope = $rootScope.$new(); and then you would use $watch against it
Right, but how i access those scopes / make ng-repeat using this scopes I created ?
this will give the number of days between two dates, but it doesn't gives the exact number of days on which the time range spreads. For instance : d1 = 06/24/2015 2PM, d2 = 06/25/02/2015 2PM the difference will give 2 days the number of days crossed by the time range will be 3 days the 2 values can be the same or not, depending on the situation. I believe the 2nd one is more interesting
2

This works, and here are 2 flawless javascript date functions you should never be without...

// Returns the days between a & b date objects...
function dateDiffInDays(a, b) {
    var _MS_PER_DAY = 1000 * 60 * 60 * 24;
    // Discard the time and time-zone information.
    var utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
    var utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
    return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}

// Calculate how many days between now and an event...
function daysTill(e) {
    var eventE = new Date(e);
    var today =  new Date();
    return dateDiffInDays(today, eventE);
}

2 Comments

How to adapter this method to calculate with minutes?
It's actually calculating the difference in miliseconds, (thousandths of a second) and dividing the result by _MS_PER_DAY to get days. So if you wanted to get minutes, you could just add a variable "divisor" to replace it and pass how many ms to divide, or change _MS_PER_DAY to be ms per minute, or = 1000 * 60 :)
0

The moment JavaScript library is really very useful and easy to use:


var parsedServerOutTime = moment(serverOutTime, "HH:mm:ss");
var parsedServerInTime = moment(serverInTime, "HH:mm:ss");

var milliseconds= parsedServerOutTime.diff(parsedServerInTime) //default milliseconds
var days = moment.duration(parsedServerOutTime .diff(parsedServerInTime )).asDays();// For days

asWeeks(); asMonths(); asYears(); etc etc for more details check http://momentjs.com/docs/

Comments

0

I tried this one to calculate the total number of days. that days calculate from date to date. so, by default to date is pick the current date.

angular.module('myApp', [])
  .controller('myCtrl', ['$scope', function($scope) {
    $scope.myFunc = function() {
      var reqDate = $scope.reqDate;
      let cDate = new Date();
      let reqSent = new Date(reqDate);
      var from = Date.UTC(cDate.getFullYear(), cDate.getMonth(),                    cDate.getDate());
      var to = Date.UTC(reqSent.getFullYear(), reqSent.getMonth(),                  reqSent.getDate());
      let day = Math.floor((from - to) /(1000 * 60 * 60 * 24));
      $scope.day = day; 
    };
  }]);
 



  
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.1/angular.min.js"></script>

<div ng-app="myApp" >
<div ng-controller="myCtrl">
    <input type='date' ng-model="reqDate" id="reqDate">
    <br />

<button ng-click="myFunc()" style="margin-top:10px;margin-bottom:10px"> Click </button> 
<br />
<b> Total Days :  {{day}}</b> 
</div>
</div>

Comments

-1

I tried the below one and it worked out for me

var selecteddate = new Date($rootscope.selectvalue);
$scope.firstDate = selecteddate .getTime();
$scope.SecondDate = new Date().getTime();

selected date is the one which is selected from calender and it is coming from parent scope. second date will be today's date. later i will find difference using moment diff.

var differenceinDays=parseInt(
      moment.duration(
        moment($scope.firstDate).diff(
          moment($scope.SecondDate)
        )
      ).asDays()
    );

I am using parseInt because i want to return the integer value only

Hope this works

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.