问题描述
我试图使用javascript添加几天给定的日期。我有以下代码
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);
}
在第一次提醒时,我收到日期 24/06 / 2011
但是在第二个警报我得到 Thu Dec 06 2012 00:00:00 GMT + 0500(巴基斯坦标准时间)
这是我想要的错它保持 24/06/2011
,以便我可以添加几天。在我的代码中,我希望我的最终输出是 25/06/2011
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
小提琴是@
推荐答案
Date('string')
将尝试解析字符串为 m / d / yyyy
。因此,字符串
24/06/2011
因此变为 2012年12月6日
。原因:24被视为一个月... 1 => 2011年1月,13 => 2012年1月,因此24 => 2012年12月。希望你明白我的意思。所以:
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()
);
这篇关于使用javascript添加日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!