0

I've got a string which represents date. I turn it into date object and count another date one month ahead. Then I want to count the difference in days between them but I don't know why both became the same and the final resault is always zero. How can I do it?

        var dateString = '2017-08-03';
        var dateFrom = new Date(dateString);
  console.log(dateFrom); //Thu Aug 03 2017 02:00:00 GMT+0200 (CEST)
  var dateTo = new Date(dateFrom.setMonth(dateFrom.getMonth()+1));

  console.log(dateTo); //Sun Sep 03 2017 02:00:00 GMT+0200 (CEST) (one month later)

  console.log(dateFrom); //Sun Sep 03 2017 02:00:00 GMT+0200 (CEST)// (two dates turn into the same)
  var difference = Math.floor((dateTo - dateFrom) / 86400000); // 0
  
Dij
  • 9,761
  • 4
  • 18
  • 35
Jacek717
  • 139
  • 1
  • 2
  • 12
  • Possible duplicate of [How do I get the number of days between two dates in JavaScript?](https://stackoverflow.com/questions/542938/how-do-i-get-the-number-of-days-between-two-dates-in-javascript) – Alice Yu Aug 03 '17 at 04:16
  • `Math.floor` should be `Math.round`. Where daylight saving is observed, one day per year is less than 24 hrs. The answer will always be the number of days in the start month, see [*What is the best way to determine the number of days in a month with javascript?*](https://stackoverflow.com/questions/315760/what-is-the-best-way-to-determine-the-number-of-days-in-a-month-with-javascript) – RobG Aug 03 '17 at 05:18

2 Answers2

0

that is happening because in var dateTo = new Date(dateFrom.setMonth(dateFrom.getMonth()+1)) you are actually changing dateFrom by setting is month to next month. you can do something like this.

    var dateString = '2017-08-03'
    var dateFrom = new Date(dateString);
    console.log(dateFrom); //Thu Aug 03 2017 02:00:00 GMT+0200 (CEST)
    var dateTo = new Date(dateString);
    dateTo = new Date(dateTo.setMonth(dateTo.getMonth()+1));

    console.log(dateTo); //Sun Sep 03 2017 02:00:00 GMT+0200 (CEST) (one month later)

    console.log(dateFrom); //Sun Sep 03 2017 02:00:00 GMT+0200 (CEST)// (two dates turn into the same)
    var difference = Math.floor((dateTo - dateFrom) / 86400000); // 0
Dij
  • 9,761
  • 4
  • 18
  • 35
0

but I don't know why both became the same and the final result is always zero.

The Ans is below line

dateFrom.setMonth(dateFrom.getMonth()+1)

You are trying to set Month month of from date and then using this updated date you are creating new date. if you to achieve desire result you may use below script .

var dateString = '2017-08-03';
var dateFrom = new Date(dateString);
console.log(dateFrom); //Thu Aug 03 2017 02:00:00 GMT+0200 (CEST)
var dateTo = new Date(dateFrom); //ADDED
dateTo =  dateTo.setMonth(dateFrom.getMonth()+1) //Updated
var difference = Math.floor((dateTo - dateFrom) / 86400000); 
Jaydip Jadhav
  • 12,179
  • 6
  • 24
  • 40