Add days to date using javascript

谁说胖子不能爱 提交于 2019-12-18 11:53:54

问题


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

function onChange(e) {
    var datepicker = $("#DatePicker").val();
    alert(datepicker);
    var joindate = new Date(datepicker);
    alert(joindate);
    var numberOfDaysToAdd = 1;
    joindate.setDate(joindate + numberOfDaysToAdd);
    var dd = joindate.getDate();
    var mm = joindate.getMonth() + 1;
    var y = joindate.getFullYear();
    var joinFormattedDate = dd + '/' + mm + '/' + y;
    $('.new').val(joinFormattedDate);
}

On first alert i get the date 24/06/2011 but on second alert i get Thu Dec 06 2012 00:00:00 GMT+0500 (Pakistan Standard Time) which is wrong i want it to remain 24/06/2011 so that i can add days to it. In my code i want my final output to be 25/06/2011

Fiddle is @ http://jsfiddle.net/tassadaque/rEe4v/


回答1:


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




回答2:


I would like to encourage you to use DateJS library. It is really awesome!

function onChange(e) {
    var date = Date.parse($("#DatePicker").val()); //You might want to tweak this to as per your needs.
    var new_date = date.add(n).days();
    $('.new').val(new_date.toString('M/d/yyyy'); //You might want to tweak this as per your needs as well.
}



回答3:


Assuming numberOfDaysToAdd is a number:

joindate.setDate(joindate.getDate() + numberOfDaysToAdd);



回答4:


The first alert is the value of the field. the second is the generated date from a non-US formatted date.

Here is a working example

(seems that this kind of markup is necessary to get noticed)

If you want to keep your code, then you need to change

var joindate = new Date(datepicker);

to

var parms = datepicker.split("/");

then use

var joindate = new Date(parms[1]+"/"+parms[0]+"/"+parms[2]);

OR the identically working

var joindate = new Date(parms[2],parms[1]-1,parms[0]);

As pointed out in a few other answers too, use the .getDate()

joindate.setDate(joindate.getDate() + numberOfDaysToAdd);

Lastly you want to add a 0 if the month is < 10

if (mm<10) mm="0"+mm;

If you are using the datepicker from jQuery UI, then you can do

$('.new').val($("#DatePicker").datepicker( "setDate" , +1 ).val());

instead of your function

http://jqueryui.com/demos/datepicker/#method-setDate

Sets the current date for the datepicker. The new date may be a Date object or a string in the current date format (e.g. '01/26/2009'), a number of days from today (e.g. +7) or a string of values and periods ('y' for years, 'm' for months, 'w' for weeks, 'd' for days, e.g. '+1m +7d'), or null to clear the selected date.




回答5:


Try

function onChange(e) {
        var datepicker = $("#DatePicker").val();
        alert(datepicker);
        var parts = datepicker.split(/[^\d]/);
        var joindate = new Date();
        joindate.setFullYear(parts[2], parts[1]-1, parts[0]);
        alert(joindate);
        var numberOfDaysToAdd = 1;
        joindate.setDate(joindate + numberOfDaysToAdd);
        var dd = joindate.getDate();
        var mm = joindate.getMonth() + 1;
        var y = joindate.getFullYear();
        var joinFormattedDate = dd + '/' + mm + '/' + y;
        $('.new').val(joinFormattedDate);

    }

I suppose the problem is JavaScript expects format MM/DD/YYYY not DD/MM/YYYY when passed into Date constructor.




回答6:


To answer your real problem, I think your issue is that you're trying to parse the text-value of the DatePicker, when that's not in the right format for your locale.

Instead of .val(), use:

var joindate = $('#DatePicker').datepicker("getDate");

to get the underyling Date() object representing the selected date directly from jQuery.

This guarantees that the date object is correct regardless of the date format specified in the DatePicker or the current locale.

Then use:

joindate.setDate(joindate.getDate() + numberOfDaysToAdd);

to move it on.




回答7:


Is it a typo round joindate.setDate(joindate + numberOfDaysToAdd)?

I tried this code, it seems ok to me

    var joindate = new Date(2010, 5, 24);
    alert(joindate);
    var numberOfDaysToAdd = 1;
    joindate.setDate(joindate.getDate() + numberOfDaysToAdd);
    var dd = joindate.getDate();
    var mm = joindate.getMonth() + 1;
    var y = joindate.getFullYear();
    var joinFormattedDate = dd + '/' + mm + '/' + y;
    alert(joinFormattedDate);



回答8:


Date.prototype.addDays = function(days) {
    this.setDate(this.getDate() + days);
    return this;
};

and in your javascript code you could call

var currentDate = new Date();
// to add 8 days to current date
currentDate.addDays(8);



回答9:


function onChange(e) {
    var datepicker = $("#DatePicker").val().split("/");
    var joindate = new Date();
    var numberOfDaysToAdd = 1;
    joindate.setFullYear(parseInt(datepicker[2]), parseInt(datepicker[1])-1, parseInt(datepicker[0])+numberOfDaysToAdd);
    $('.new').val(joindate);
}

http://jsfiddle.net/roberkules/k4GM5/




回答10:


try this.

Date.prototype.addDay = function(numberOfDaysToAdd){
    this.setTime(this.getTime() + (numberOfDaysToAdd * 86400000));
};

function onChange(e) {
        var date = new Date(Date.parse($("#DatePicker").val()));
        date.addDay(1);
        var dd = date.getDate();
        var mm = date.getMonth() + 1;
        var y =  date.getFullYear();
        var joinFormattedDate = dd + '/' + mm + '/' + y;
        $('.new').val(joinFormattedDate);
    }



回答11:


var day = 24*60*60*1000; // One day = 24 hours * 60 min * 60 sec * 1000 mili sec
var numOfDays = 5 * day;
var numOfDaysLaterDate  = new Date((new Date()).valueOf() + numOfDays);


来源:https://stackoverflow.com/questions/6368153/add-days-to-date-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!