我正在尝试根据用户的选择生成时间戳。
我有一个输入值为空的表单:
<input type="hidden" name="sub_enddate" value=" " />
我需要根据用户选择的未来某个时间值填写空值:
<select name="Membership Duration">
<option value="">Select A Membership Duration</option>
<option class="6" value="6 Months">6 Month Membership</option>
<option class="3" value="3 Months">3 Month Membership</option>
<option class="1" value="1 Months">1 Month Membership</option>
</select>
格式如下:20110325(2011-03-25)。因此,如果用户从下拉菜单中选择:
答案 0 :(得分:1)
$('select').change(function(){
var months = $(this).val().replace(' Months', '')*1,
today = new Date(),
expiration = new Date(today.setMonth(today.getMonth() + months)),
month = expiration.getMonth() < 9 ? '0' + (expiration.getMonth() + 1) : (expiration.getMonth() +1) + '',
date = expiration.getDate() < 10 ? '0' + expiration.getDate() : expiration.getDate() + '',
formatted = expiration.getFullYear() + month + date;
$('input[name="sub_enddate"]').val(formatted);
});
答案 1 :(得分:0)
See example of the following →
这应该做的伎俩:
$('#mem_dur').change(function(e) {
var tVal = $(this).find('option:selected').val()[0],
tDate = new Date(),
mDate, mDateMS, mDateStr
oneMonth = 31 * 86400000;
mDateMS = tDate.getTime() + tVal * oneMonth;
mDate = new Date(mDateMS);
mDateStr = String(mDate.getFullYear()) +
((mDate.getMonth() < 9) ? "0" + (mDate.getMonth() + 1) : mDate.getMonth() + 1) +
((mDate.getDate() < 10) ? "0" + mDate.getDate() : mDate.getDate());
mDateStr = (isNaN(parseInt(mDateStr,10))) ? "" : mDateStr;
$('#sub_enddate').val(mDateStr);
});
答案 2 :(得分:0)
基本上,setMonth
和getMonth
函数是最重要的。
我做了这个:http://jsfiddle.net/TrsNX/1/。
Number.prototype.fillUpWithZeroes = function() {
// function to make a number like 3 formatted to 03.
return (this + "").length === 1 ? "0" + this : "" + this;
}
$('select').change(function() {
var time_now = new Date; // current time
var chosen_value = $(this).val(); // chosen amount of months
var time_in_future = new Date( // construct future time using value
time_now.setMonth(
time_now.getMonth()
+ (chosen_value-0)
)
);
var year = time_in_future.getFullYear(); // format everything
var month = (time_in_future.getMonth() + 1).fillUpWithZeroes();
// Month starts at 0 (January)! So add 1.
var date = time_in_future.getDate().fillUpWithZeroes();
var formatted = year + month + date;
$('input').val(formatted);
});