简体   繁体   中英

how to change previous date and current date in javascript?

I have an application where I have to display records between two dates, current date and previous date. By default 6 months data are displayed(which is a part of my requirement) but I want to change my previous date during run time(I am passing it from UI) and I don't want to pick future date as current date. Below is my code, please help me to solve this, thank you

// ------------------- function to change dates --------------------- 
    function changeDates(){        
            var date = new Date();
            var cur_date = new Date(date.getFullYear(), date.getMonth() + 1, 0);
            cur_date = cur_date.toString("yyyy-MM-dd");
            cur_date = cur_date.trim();
            var pre_date = new Date(date.getFullYear(), date.getMonth() - 5, 1);
            pre_date = pre_date.toString("yyyy-MM-dd");
            pre_date = pre_date.trim();
            var xmlhttp;
            xmlhttp.open("GET","dashboard/Ajax/change_date.jsp?pre_date="+pre_date+"&cur_date="+cur_date,true);
        xmlhttp.send();

}

From what I can see there are two questions here: 1) Your current date is being created as a future date and 2) You want to be able to override the default pre_date value.

First, when you are calling the Date constructor you are adding a month. This is not necessary. I would read through the MDN on Date .

var cur_date = new Date(date.getFullYear(), date.getMonth(), 1).toString();

Second, the function makes no attempt to change the value of pre_date to override the default. Have the function accept the override date

function changeDates(previousDate)

Then override if a date was passed (you may want to validate the date further):

     var pre_date = previousDate ? 
         previousDate : 
         new Date(date.getFullYear(), date.getMonth() - 5, 1).toString();

Also, I would add that the toString() method does not take any arguments and there should be no need to trim the result.

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