Angularjs Date Subtraction

Asked

Viewed 899 times

4

Good, How do I subtract a day with the angle

 old.endDay = start.startDay;

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

I’m sorry I said that wrong. actually I wanted to strip one day of startDay and send the change to endDay.

Thank you!

  • 1

    You can use lib Moment js to handle dates. It will be much easier using this lib, because handling dates in javascript in hand is boring as hell. hehe

  • Yes but I think this project I’m working on has enough lib, thank you

  • Bruno, did any of the answers solve your problem?

  • 1

    Yes, they all helped me to arrive at the solution and to think differently, thank you

3 answers

7

You can use a library or do this 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>

Using Native Javascript:

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

  • 1

    +1 for using dd/mm/yyyy as requested by OP.

4


Angularjs stores the values of data type controls using the date object Javascript. To subtract two dates, you can use the method .getTime() which returns the number of milliseconds passed between the date in question and January 1, 1970 (GMT).

Then, by converting the two, you can subtract from each 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!");

1

Good I find out what was happening my date had the wrong format when coming from the bank, so I did this:

    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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.