Javascript 添加 30 天至今 (mm/dd/yy)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5930862/
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-23 19:33:39  来源:igfitidea点击:

Add 30 days to date (mm/dd/yy)

javascriptdate

提问by Jim

I have a date in the format mm/dd/yyand want to add 30 days to it. I am just curious the best method to do this? I am new to javascript so examples would be helpful.

我有一个格式的日期,mm/dd/yy并想为其添加 30 天。我只是好奇这样做的最佳方法是什么?我是 javascript 新手,所以示例会有所帮助。

EDITED

已编辑

Sorry I am using US date format mm/dd/yy.

抱歉,我使用的是美国日期格式mm/dd/yy

回答by RobG

Updated answer (2018)

更新答案 (2018)

One way to add 30 days to a date string is to parse it to a Date, add 30 days, then format it back to a string.

将 30 天添加到日期字符串的一种方法是将其解析为日期,添加 30 天,然后将其格式化回字符串。

Date strings should be parsed manually, either with a bespoke function or a library. Either way, you need to know the format to know if it's been parsed correctly, e.g.

应该使用定制函数或库手动解析日期字符串。无论哪种方式,您都需要知道格式才能知道它是否被正确解析,例如

// Given a string in m/d/y format, return a Date
function parseMDY(s) {
  var b = s.split(/\D/);
  return new Date(b[2], b[0]-1, b[1]);
}

// Given a Date, return a string in m/d/y format
function formatMDY(d) {
  function z(n){return (n<10?'0':'')+n}
  if (isNaN(+d)) return d.toString();
  return z(d.getMonth()+1) + '/' + z(d.getDate()) + '/' + d.getFullYear();
}

// Given a string in m/d/y format, return a string in the same format with n days added
function addDays(s, days) {
  var d = parseMDY(s);
  d.setDate(d.getDate() + Number(days));
  return formatMDY(d);
}

[['6/30/2018', 30],
 ['1/30/2018', 30], // Goes from 30 Jan to 1 Mar
 ['12/31/2019', 30]].forEach(a => {
  console.log(`${a[0]} => ${addDays(...a)}`);
});

If the "30 days" criterion is interpreted as adding a month, that is a bit trickier. Adding 1 month to 31 January will give 31 February, which resolves to 2 or 3 March depending on whether February for that year has 28 or 29 days. One algorithm to resolve that is to see if the month has gone too far and set the date to the last day of the previous month, so 2018-01-31 plus one month gives 2018-02-28.

如果将“30 天”标准解释为增加一个月,那就有点棘手了。将 1 个月添加到 1 月 31 日将得到 2 月 31 日,根据该年的 2 月是 28 天还是 29 天,最终确定为 3 月 2 日或 3 日。解决该问题的一种算法是查看该月是否走得太远,并将日期设置为上个月的最后一天,因此 2018-01-31 加上一个月得出 2018-02-28。

The same algorithm works for subtracting months, e.g.

相同的算法适用于减去月份,例如

/**
 * @param {Date} date - date to add months to
 * @param {number} months - months to add
 * @returns {Date}
*/
function addMonths(date, months) {

  // Deal with invalid Date
  if (isNaN(+date)) return;
  
  months = parseInt(months);

  // Deal with months not being a number
  if (isNaN(months)) return;

  // Store date's current month
  var m = date.getMonth();
  date.setMonth(date.getMonth() + months);
  
  // Check new month, if rolled over an extra month, 
  // go back to last day of previous month
  if (date.getMonth() != (m + 12 + months)%12) {
    date.setDate(0);
  }
  
  // date is modified in place, but return for convenience
  return date;
}

// Helper to format the date as D-MMM-YYYY
// using browser default language
function formatDMMMY(date) {
  var month = date.toLocaleString(undefined,{month:'short'});
  return date.getDate() + '-' + month + '-' + date.getFullYear();
}

// Some tests
[[new Date(2018,0,31),  1],
 [new Date(2017,11,31), 2],
 [new Date(2018,2,31), -1],
 [new Date(2018,6,31), -1],
 [new Date(2018,6,31), -17]].forEach(a => {
   let f = formatDMMMY;
   console.log(`${f(a[0])} plus ${a[1]} months: ${f(addMonths(...a))}`); 
});

Of course a library can help with the above, the algorithms are the same.

当然,库可以帮助解决上述问题,算法是相同的。

Original answer (very much out of date now)

原始答案(现在已经过时了)

Simply add 30 days to todays date:

只需将今天的日期加上 30 天:

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

However, is that what you really want to do? Or do you want to get today plus one month?

然而,这真的是你想做的吗?或者你想得到今天加一个月?

You can convert a d/m/y date to a date object using:

您可以使用以下方法将 ad/m/y 日期转换为日期对象:

var dString = '9/5/2011';
var dParts = dString.split('/');
var in30Days = new Date(dParts[2] + '/' +
                        dParts[1] + '/' +
                        (+dParts[0] + 30)
               );

For US date format, swap parts 0 and 1:

对于美国日期格式,交换部分 0 和 1:

var in30Days = new Date(dParts[2] + '/' +
                        dParts[0] + '/' +
                        (+dParts[1] + 30)
               );

But it is better to get the date into an ISO8601 format before giving it to the function, you really shouldn't be mixing date parsing and arithmetic in the same function. A comprehensive date parsing function is complex (not excessively but they are tediously long and need lots of testing), arithmetic is quite simple once you have a date object.

但是最好在将日期提供给函数之前将日期转换为 ISO8601 格式,您真的不应该在同一个函数中混合日期解析和算术。一个全面的日期解析函数很复杂(不过分但它们冗长乏味,需要大量测试),一旦你有了一个日期对象,算术就很简单了。

回答by Alberto Mendoza

A simple way to get it done is to send the timestamp value in the Dateconstructor. To calculate 30 days measured in timestamp:

完成它的一个简单方法是在Date构造函数中发送时间戳值。要计算以时间戳衡量的 30 天:

30 * 24 * 60 * 60 * 1000

30 * 24 * 60 * 60 * 1000

Then, you need the current timestamp:

然后,您需要当前时间戳:

Date.now()

Date.now()

Finally, sum both values and send the result as a param in the constructor:

最后,将两个值相加并将结果作为参数发送到构造函数中:

var nowPlus30Days = new Date(Date.now() + (30 * 24 * 60 * 60 * 1000));

var nowPlus30Days = new Date(Date.now() + (30 * 24 * 60 * 60 * 1000));

回答by Kamil Kie?czewski

try

尝试

new Date(+yourDate - 30 *86400000)

var yourDate = new Date() 
var newDate = new Date(+yourDate - 30 *86400000)

console.log(newDate)