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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7908098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:01:12  来源:igfitidea点击:

Javascript - Set date 30 days from now

javascriptjquery

提问by Victor

I need to set a date that would be 30 days from now taking into account months that are 28,29,30,31 days so it doesn't skip any days and shows exactly 30 days from now. How can I do that?

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

回答by Pointy

The JavaScript "Date()" object has got you covered:

JavaScript“Date()”对象已为您提供帮助:

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

That'll just do the right thing. (It's a little confusing that the getter/setters for day-of-month have the names they do.)

那只会做正确的事情。(每月某天的 getter/setter 具有它们的名称,这有点令人困惑。)

回答by timrwood

I wrote a Date wrapper library that helps with parsing, manipulating, and formatting dates.

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

https://github.com/timrwood/moment

https://github.com/timrwood/moment

Here is how you would do it with Moment.js

以下是使用 Moment.js 的方法

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

回答by Rich Apodaca

Using the native Date object with straightforward syntax and no external libraries:

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

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

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

The Date setTime and getTime functions use milliseconds since Jan 1, 1970 (link).

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

回答by Domenic

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

回答by nurealam siddiq

Try this piece of code:

试试这段代码:

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

回答by Ron Kinkade

I've been able to make this work:

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

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());
}