AngularJS Date subtraction

4

Well, How do I subtract a day from the angle

 old.endDay = start.startDay;

Example: startDay = 05/05/2017. endDay = 04/30/2017.

I'm sorry.  in fact I wanted was to take day out of startDay and send the change to endDay.

Thank you!

    
asked by anonymous 14.06.2017 / 14:04

3 answers

4

AngularJS saves the values of date type controls using the Date object . To subtract two dates, you can use the .getTime() method that returns the number of milliseconds passed between that date and January 1, 1970 (GMT).

Then, by converting the two, you can subtract one from the other and find the number of milliseconds between one and the other. Divide the result by (24 * 60 * 60 * 1000) and you have the number of days between the two dates.

var dias = (startDay.getTime() - endDay.getTime()) / 86400000;
if (dias == 1) console.log("Correto!");
    
14.06.2017 / 14:19
6

You can use a library or do it natively.

Using Moment.js :

var a = moment('01/05/2017', 'DD/MM/YYYY');
console.log(
  a.diff(moment('30/04/2017', 'DD/MM/YYYY'),
    'days')
); // dá 1

console.log(
  a.diff(moment('01/04/2017', 'DD/MM/YYYY'),
    'days')
); // dá 30
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.2.1/moment.js"></script>

UsingnativeJavaScript:

function dateFrom(string) {
  var partes = string.split('/');
  return new Date(partes[2], partes[1] - 1, partes[0]); 
}

function dateDiff(a, b) {
  var diff = dateFrom(a) - dateFrom(b);
  return Math.round(diff / 864e5);
}

console.log(dateDiff('01/05/2017', '30/04/2017')); // dá 1
console.log(dateDiff('01/05/2017', '01/04/2017')); // dá 30
    
14.06.2017 / 14:21
1

Well I figured out what was happening my date had the wrong format when it came from the bank, so I did it:

    var data_do_banco = start.startDay.replace("-", " ").replace("-", " ").substring(0, 10);
    var nova_data = new Date(data_do_banco);
    nova_data = nova_data.setDate(nova_data.getDate() - 1);
    old.endDay = nova_data;

Thanks for the help.

    
14.06.2017 / 16:30