javascript日期+ 7天

use*_*285 43 javascript jquery date

这个脚本有什么问题?

当我设置我的时钟说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);
    }
Run Code Online (Sandbox Code Playgroud)

ada*_*m77 114

var date = new Date();
date.setDate(date.getDate() + 7);

console.log(date);
Run Code Online (Sandbox Code Playgroud)

是的,如果date.getDate() + 7大于该月的最后一天,这也有效.有关更多信息,请参阅MDN.

  • 如果你添加超过31天,这甚至可以工作! (6认同)
  • @CodeMonkey超过1个月;) (3认同)

Ema*_*uel 15

无需声明

返回时间戳

new Date().setDate(new Date().getDate() + 7)
Run Code Online (Sandbox Code Playgroud)

返回日期

new Date(new Date().setDate(new Date().getDate() + 7))
Run Code Online (Sandbox Code Playgroud)


Mar*_*oLe 14

一行:

new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
Run Code Online (Sandbox Code Playgroud)

  • 让这家伙休息一下,这是一个非常好的和简单的单行,可以完成这项工作,没有凌乱的临时内容。 (6认同)
  • 他想知道为什么他的代码不起作用。隐含地他也想知道如何获得7天后的日期。我提供了答案。 (3认同)
  • 谢谢!这正是我所需要的。为了我的目的稍微修改了它,我需要一个纪元时间,所以我使用:Math.floor((Date.now() + 7 * 24 * 60 * 60 * 1000)/1000) - 希望这对某人有用其他也一样! (2认同)

ezm*_*use 11

像这样的东西?

var days = 7;
var date = new Date();
var res = date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
alert(res);
Run Code Online (Sandbox Code Playgroud)

再次转换为日期:

date = new Date(res);
alert(date)
Run Code Online (Sandbox Code Playgroud)

或者:

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)
Run Code Online (Sandbox Code Playgroud)


Rob*_*obG 6

获取日期x天的简单方法是增加日期:

function addDays(dateObj, numDays) {
  return dateObj.setDate(dateObj.getDate() + numDays);
}
Run Code Online (Sandbox Code Playgroud)

请注意,这会修改提供的日期对象,例如

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
);
Run Code Online (Sandbox Code Playgroud)


Jak*_*mpl 0

这里有两个问题:

  1. seven_date是一个数字,而不是日期。29 + 7 = 36
  2. getMonth返回月份的从零开始的索引。所以加一就可以得到当前月份的数字。