简体   繁体   中英

Javascript setdate getDate()+28 returns bad

I am getting a weird output when trying to add days to a date value.

var startdate = $("#JobStartDate").val();

startdate = new Date(startdate);
startdate28 = startdate.setDate(startdate.getDate()+28);

console.log(startdate);
console.log(startdate28);

results in

startdate = "Date 2017-03-15T00:00:00.000Z"

startdate28 = 1489536000000

any ideas where i am going wrong?

like so:

var startdate = $("#JobStartDate").val();

startdate = new Date(startdate);
startdate28 = new Date();
startdate28.setDate(startdate.getDate()+28);

console.log(startdate);
console.log(startdate28);

Have a look at the following code snippet:

 var startdate = "2017-02-15"; startdate = new Date(startdate); startdate28 = new Date(); startdate28.setTime(startdate.getTime() + 28 * 86400000); console.log(startdate); console.log(startdate28); 

Notice that you need to us setTime intead of setDate as that may cause errors when the month or year isn't the same as the one before adding the days.

The result will be:

"2017-02-15T00:00:00.000Z"

"2017-03-15T00:00:00.000Z"

for this line: startdate28 = startdate.setDate(startdate.getDate()+28); You store what returns from "startdate.setDate" inside "startdate28" and this function return the time stamp for the adjusted date.

What you can do is to create a new date object for the other date:

var startdate = '2016-01-01';

startdate = new Date(startdate);
startdate28 = new Date(startdate.setDate(startdate.getDate()+28));

console.log(startdate);
console.log(startdate28);

the method Date.getDate() results in an integer. So, integer+28 is still an integer and not a Date type. Try:

var startdate;
startdate = new Date("2017-03-15T00:00:00.000Z"); 
startdate28 = new Date();
startdate28.setDate(startdate.getDate()+28);
console.log(startdate); 
console.log(startdate28);

here you go:

addDays = function(days) {
    var startdate = new Date(this.valueOf());
    startdate.setDate(startdate.getDate() + days);
    return startdate;
}

var startdate= new Date();

alert(dat.addDays(5))

I had the same problem and the solution I've found is as followed:

var startdate = "2017-02-15";
startdate = new Date(startdate);
startdate28 = new Date(startdate.setDate(startdate.getDate()+28));

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