我继承了一个包含现有JavaScript的表单,该表单从今天开始创建一个新日期+ 3个月。
var monthAway = new Date(new Date);
var day =monthAway.getDate();
var month =monthAway.getMonth() + 3;
var year =monthAway.getFullYear();
$('#Date_for_Second_Store_Access_to_Expire').val(day + "/" + month + "/" + year);
<p><input id="Date_for_Second_Store_Access_to_Expire" type="hidden" name="Date_for_Second_Store_Access_to_Expire" class="required" /></p>
问题是,如果今天的日期是十月,十一月或十二月,则新的日期月份将是13,14或15而不是更新为1,2或3,然后更新年份,例如2014年5月11日是05/14/2014而不是05/02/2015。
有什么想法吗?
答案 0 :(得分:2)
试试这个:
var x = 3; //or whatever offset
var CurrentDate = new Date();
CurrentDate.setMonth(CurrentDate.getMonth() + x);
alert(CurrentDate);
答案 1 :(得分:1)
使用setMonth method添加3个月到monthAway
变量,如下所示
monthAway.setMonth(monthAway.getMonth() + 3);
然后只需使用修改后的monthAway
即可显示到期日期。请注意getMonth() Method将返回0-11,其中0表示1月,1表示2月,...,11表示12月,因此您需要执行此操作以显示正确的月份
var month = monthAway.getMonth() + 1;
这是完整修改后的代码,假设代码今天执行(#Date_for_Second_Store_Access_to_Expire
),5/2/2015
的值将为5/11/2014
。
var monthAway = new Date(new Date);
monthAway.setMonth(monthAway.getMonth() + 3); // add 3 months to monthAway
var day = monthAway.getDate();
var month = monthAway.getMonth() + 1; // add 1 because .getMonth returns zero based month
var year = monthAway.getFullYear();
$('#Date_for_Second_Store_Access_to_Expire').val(day + "/" + month + "/" + year);
<p><input id="Date_for_Second_Store_Access_to_Expire" type="hidden" name="Date_for_Second_Store_Access_to_Expire" class="required" /></p>
这是JSFiddle,显示上述代码中day + "/" + month + "/" + year
的值:http://jsfiddle.net/jwa6o6r2/
答案 2 :(得分:0)
在增加month
变量时进行简单的检查:
var month = monthAway.getMonth() + 3;
if(month > 12) //If it crosses 12, start from 1 again.
month -= 12;
答案 3 :(得分:0)
更改
var month = monthAway.getMonth() + 3;
要
var month = ((monthAway.getMonth() + 3) % 12) + 1;
((monthAway.getMonth() + 3) % 12)
将为您提供0到11之间的数字。因为您需要1-12,+ 1
所在的位置。
对于年度问题,请尝试以下
var year = (month <= 3 ? monthAway.getFullYear() + 1 : monthAway.getFullYear());
这将检查月份是否小于或等于3,这只有在你被缠住的情况下才有可能。