从JavaScript中的日期中减去天,月,年
有谁知道约会(例如今天)并回溯X天,X个月和X年的简单方法吗?
我已经尝试过:
var date = new Date();
$("#searchDateFrom").val((date.getMonth() -1 ) + '/' + (date.getDate() - 6) + '/' + (date.getFullYear() - 1));
但是我得到一个负日期,例如今天的输出是:
3/-3/2015
有什么建议吗?
谢谢。
user3378165 asked 2020-07-03T00:02:13Z
6个解决方案
68 votes
您只是从一个数字中减少了值。 因此,从3(日期)中减去6将仅返回-3。
您需要在日期对象中单独添加/删除时间单位
var date = new Date();
date.setDate( date.getDate() - 6 );
date.setFullYear( date.getFullYear() - 1 );
$("#searchDateFrom").val((date.getMonth() ) + '/' + (date.getDate()) + '/' + (date.getFullYear()));
gurvinder372 answered 2020-07-03T00:02:31Z
17 votes
正如其他人所说,您要从date.getDate()之类的方法返回的数值中减去,您需要在date变量上重置这些值。 我在下面创建了一个可以为您完成此操作的方法。 它使用new Date()创建一个日期,该日期将使用当前日期进行初始化,然后根据传入的值设置日期,月份和年份。例如,如果要返回6天,则像var newdate = createDate(-6,0,0)那样传入-6。 如果您不想设置值,请传入零(或者可以设置默认值)。 该方法将为您返回新日期(已在Chrome和Firefox中测试)。
function createDate(days, months, years) {
var date = new Date();
date.setDate(date.getDate() + days);
date.setMonth(date.getMonth() + months);
date.setFullYear(date.getFullYear() + years);
return date;
}
Phil answered 2020-07-03T00:02:52Z
14 votes
我建议使用MomentJS库。 它们使与Dates的所有交互变得更加简单。
如果使用Moment,您的代码将像这样简单:
var today = moment();
var nextMonth = today.add('month', 1);
您可以在以下位置找到MomentJS:[http://momentjs.com/]
更新:
在JavaScript中,Date.getDate()函数返回从1-31开始的当前日期。 您将从这个数字中减去6,目前是该月的3号。 这将值带到-3。
FvB answered 2020-07-03T00:03:30Z
4 votes
这是一个纯函数,需要以传递的开始日期为基础,以Phil的答案为基础:
function deltaDate(input, days, months, years) {
var date = new Date(input);
date.setDate(date.getDate() + days);
date.setMonth(date.getMonth() + months);
date.setFullYear(date.getFullYear() + years);
return date;
}
例如 将一个月前的日期写入控制台日志:
console.log(deltaDate(new Date(), 0, -1, 0));
请注意,即使您在月底或年份结束时也可以使用。
N8allan answered 2020-07-03T00:03:59Z
2 votes
使用moment.js库进行时间和日期管理。
import moment = require('moment');
const now = moment();
now.subtract('seconds', 7); // takes 7 seconds of the current time
now.subtract('days', 7); // takes 7 days of the current date
now.subtract('months', 7); // takes 7 months of the current date
now.subtract('years', 7); // takes 7 years of the current date
Younes Henni answered 2020-07-03T00:04:18Z
0 votes
这不能完全回答问题,但是对于任何能够计算希望抵消初始日期的天数的人,以下方法将起作用:
myDate.setUTCDate(myDate.getUTCDate() + offsetDays);
offsetDays可以是正数或负数,并且对于任何给定的初始日期和任何给定的偏移量,结果都是正确的。
Alan Gee answered 2020-07-03T00:04:43Z