简体   繁体   中英

How do I create date dynamically in javascript?

let date = new Date();
 let days = 
['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
let months = ['January','February','March','April','May','June','July','August','September',' 
  October','November','December'];





 alert(days[date.getDay(1)])
 alert( months[date.setMonth(3)]) 
 alert(date.setDate(30))

let add = document.getElementById("add");
add.addEventListener('click',function generateHTML(){
let parentselector = document.querySelector('section');
let tagname = document.createElement('div');
parentselector.appendChild(tagname);
tagname.className = "tagname";
let childelement1 = document.createElement('div')
childelement1.className = 'number0'
tagname.appendChild(childelement1)
   for(k = 1; k < 16; k++){
    let  childelement = document.createElement('div');
     tagname.appendChild(childelement);
     childelement.className = "number";
     childelement.classList.add(`number${k}`)
     childelement.style.backgroundColor ='red'
     let text = document.createTextNode('0')
     childelement.appendChild(text) 
   }
   tagname.firstElementChild.style.backgroundColor = 'green'

  yes();
    })




 let remove = document.getElementById("remove");
  remove.addEventListener('click', function remove() {
    let elem = document.getElementsByClassName("tagname")
    elem[elem.length-1].remove();


  })

I am creating days dynamically in my javascript code by clicking add button and removing last added day by clicking remove button. Now what I want to do is to start adding dates from Mon April 30 (in this format) and increasing it with 2,2,1,2 intervals.So first week should contain Mon April 30, Wed May 2, Fri May 4, Sat May 5, Mon May 7, and so on. and when I push remove button I want it to remove the last date added with entire column and add the same date after clicking add button.This dates should be written in the divs with class number0.How do I do this with javasript only?

One way is to create start date as 30th April. Then each time you call getNextDate() function, it will return new date in respect of increments interval.

var startDate = new Date(new Date('04/30/2018').getTime());
var increments = [2,2,1,2];
var nextIncrementIndex = 0;

function getNextDate(){

    var increment = increments[nextIncrementIndex];
    nextIncrementIndex+= 1;
    if(increment === undefined){
        increment = increments[0];
        nextIncrementIndex = 1;
    }
    var nextDate = startDate;
    nextDate.setDate(startDate.getDate() + increment );
    return nextDate;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM