Add days to date using javascript

前端 未结 10 1304
执笔经年
执笔经年 2020-12-29 12:21

I am trying to add days to a given date using javascript. I have the following code

function onChange(e) {
    var datepicker = $(\"#DatePicker\").val();
           


        
10条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-29 12:37

    Date('string') will attempt to parse the string as m/d/yyyy. The string 24/06/2011 thus becomes Dec 6, 2012. Reason: 24 is treated as a month... 1 => January 2011, 13 => January 2012 hence 24 => December 2012. I hope you understand what I mean. So:

    var dmy = "24/06/2011".split("/");        // "24/06/2011" should be pulled from $("#DatePicker").val() instead
    var joindate = new Date(
        parseInt(dmy[2], 10),
        parseInt(dmy[1], 10) - 1,
        parseInt(dmy[0], 10)
    );
    alert(joindate);                          // Fri Jun 24 2011 00:00:00 GMT+0500 (West Asia Standard Time) 
    joindate.setDate(joindate.getDate() + 1); // substitute 1 with actual number of days to add
    alert(joindate);                          // Sat Jun 25 2011 00:00:00 GMT+0500 (West Asia Standard Time)
    alert(
        ("0" + joindate.getDate()).slice(-2) + "/" +
        ("0" + (joindate.getMonth() + 1)).slice(-2) + "/" +
        joindate.getFullYear()
    );
    

    Demo here

提交回复
热议问题