Skip to content
Advertisement

javascript date String array push issue! Not the desired value

I’d like to get a date between the start and end dates

  d = 'Tue Oct 2 00:00:00 UTC+0900 2018';
  date2 = 'Fri Oct 5 00:00:00 UTC+0900 2018';

  var arrTemp = new Array();
  //var dispalyHTML = '';

while(d <= date2){
  //dispalyHTML += d.yyyymmdd();
  var date_yy = d.getFullYear();
  var date_mm = (d.getMonth()+1) < 10 ? '0' +(d.getMonth()+1):(d.getMonth()+1);
  var date_dd = d.getDate() <10 > '0'+d.getDate():d.getDate();

  alert("date_yy+date_mm+date_dd=="+date_yy+date_mm+date_dd);

  **arrTemp.push(date_yy+date_mm+date_dd);**
  d = d.addDays(1);
}


for(j=0; j < arrTemp.length; j++){

    alert("arrTemp[j]=="+arrTemp[j]);
 }

The first value, is the desired value. be worth!

 date_yy+date_mm+date_dd==20181002
 date_yy+date_mm+date_dd==20181003
 date_yy+date_mm+date_dd==20181004
 date_yy+date_mm+date_dd==20181005

BUT arrTemp[j] value, Not the desired value.

arrTemp[j]==202802
arrTemp[j]==202803
arrTemp[j]==202804
arrTemp[j]==202805

Do you know why?

Advertisement

Answer

Use moment, never try and roll your own date functions.

let date1 = moment('02/10/2018', 'DD/MM/YYYY');
let date2 = moment('05/10/2018', 'DD/MM/YYYY');
 
let noOfDays = moment(date2).diff(moment(date1), 'days') + 1;
 
days = (date, noOfDays) => Array.from(Array(noOfDays), (_, i) => moment(date, 'DD/MM/YYYY').add(i, 'd').format('YYYYMMDD'));
 
console.log(days('02/10/2018', noOfDays));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement