javascript日期+ 7天
这个脚本有什么问题?
当我把我的时钟设置为29/04/2011时,它会在本周输入中添加36/4/2011 ! 但正确的日期应该是6/5/2011
var d = new Date(); var curr_date = d.getDate(); var tomo_date = d.getDate()+1; var seven_date = d.getDate()+7; var curr_month = d.getMonth(); curr_month++; var curr_year = d.getFullYear(); var tomorrowsDate =(tomo_date + "/" + curr_month + "/" + curr_year); var weekDate =(seven_date + "/" + curr_month + "/" + curr_year); { jQuery("input[id*='tomorrow']").val(tomorrowsDate); jQuery("input[id*='week']").val(weekDate); }
var date = new Date(); date.setDate(date.getDate() + 7); console.log(date);
像这样的东西?
var days = 7; var date = new Date(); var res = date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); alert(res);
再次转换为日期:
date = new Date(res); alert(date)
或者:
date = new Date(res); // hours part from the timestamp var hours = date.getHours(); // minutes part from the timestamp var minutes = date.getMinutes(); // seconds part from the timestamp var seconds = date.getSeconds(); // will display time in 10:30:23 format var formattedTime = date + '-' + hours + ':' + minutes + ':' + seconds; alert(formattedTime)
获取日期x天的简单方法是增加日期:
function addDays(dateObj, numDays) { return dateObj.setDate(dateObj.getDate() + numDays); }
请注意,这会修改提供的日期对象,例如
function addDays(dateObj, numDays) { dateObj.setDate(dateObj.getDate() + numDays); return dateObj; } var now = new Date(); var tomorrow = addDays(new Date(), 1); var nextWeek = addDays(new Date(), 7); alert( 'Today: ' + now + '\nTomorrow: ' + tomorrow + '\nNext week: ' + nextWeek );
var days = 7; var date = new Date(); var res = date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); var d = new Date(res); var month = d.getMonth() + 1; var day = d.getDate(); var output = d.getFullYear() + '/' + (month < 10 ? '0' : '') + month + '/' + (day < 10 ? '0' : '') + day; $('#txtEndDate').val(output);
您可以为以下示例添加或增加星期几,希望这对您有所帮助。让我们看看….
//Current date var currentDate = new Date(); //to set Bangladeshi date need to add hour 6 currentDate.setUTCHours(6); //here 2 is day increament for the date and you can use -2 for decreament day currentDate.setDate(currentDate.getDate() +parseInt(2)); //formatting date by mm/dd/yyyy var dateInmmddyyyy = currentDate.getMonth() + 1 + '/' + currentDate.getDate() + '/' + currentDate.getFullYear();
这里有两个问题:
-
seven_date
是一个数字,而不是日期。29 + 7 = 36
-
getMonth
返回基于零的月份索引。 因此添加一个只会获得当前月份数。
使用Date对象的方法 将 可以派上用场。
例如:
myDate = new Date(); plusSeven = new Date(myDate.setDate(myDate.getDate() + 7));