Javascript - 从现在起30天后设置日期

时间:2011-10-26 19:55:04

标签: javascript jquery

我需要设置一个从现在开始30天的日期,考虑28,29,30,31天的月份,因此它不会跳过任何日期,并且显示从现在开始的30天。我怎么能这样做?

6 个答案:

答案 0 :(得分:29)

JavaScript“Date()”对象已经涵盖了你:

var future = new Date();
future.setDate(future.getDate() + 30);

那就是做正确的事。 (有点令人困惑的是,每月的吸气剂/安装者都有自己的名字。)

答案 1 :(得分:6)

我写了一个Date包装器库,它有助于解析,操作和格式化日期。

https://github.com/timrwood/moment

以下是使用Moment.js

的方法
var inThirtyDays = moment().add('days', 30);

答案 2 :(得分:3)

var now = new Date();
var THIRTY_DAYS = 30 * 24 * 60 * 60 * 1000;
var thirtyDaysFromNow = now + THIRTY_DAYS;

答案 3 :(得分:3)

使用具有简单语法的本机Date对象而不使用外部库:

var future = new Date('Jan 1, 2014');

future.setTime(future.getTime() + 30 * 24 * 60 * 60 * 1000); // Jan 31, 2014

Date setTime和getTime函数使用1970年1月1日以来的毫秒数(link)。

答案 4 :(得分:0)

尝试这段代码:

const date = new Date();
futureDate = new Date(date.setDate(date.getDate() + 30)).toLocaleDateString();

答案 5 :(得分:-1)

我已经能够完成这项工作:

function() {
// Get local time as ISO string with offset at the end
var now = new Date();
now.setMonth(now.getMonth() + 1);
var pad = function(num) {
    var norm = Math.abs(Math.floor(num));
    return (norm < 10 ? '0' : '') + norm;
};
return now.getFullYear() 
    + '-' + pad(now.getMonth()+1)
    + '-' + pad(now.getDate());
}
相关问题