Javascript 如何从jquery中的这个日期减去一周?

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

how do I subtract one week from this date in jquery?

javascriptjquery

提问by Infinity

this is my code

这是我的代码

var myDate = new Date();
todaysDate = ((myDate.getDate()) + '/' + (myDate.getMonth()) + '/' + (myDate.getFullYear()));
$('#txtEndDate').val(todaysDate);

I need txtEndDate's value = today's date - one week

我需要 txtEndDate 的值 = 今天的日期 - 一周

回答by dxh

You can modify a date using setDate. It automatically corrects for shifting to new months/years etc.

您可以使用 修改日期setDate。它会自动纠正转移到新的月份/年份等。

var oneWeekAgo = new Date();
oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);

And then go ahead to render the date to a string in any matter you prefer.

然后继续以任何您喜欢的方式将日期呈现为字符串。

回答by Jean-Philippe Gire

I'd do something like

我会做类似的事情

var myDate = new Date();
var newDate = new Date(myDate.getTime() - (60*60*24*7*1000));

回答by Sandeep G B

var now = new Date();
now.setDate(now.getDate() - 7); // add -7 days to your date variable 
alert(now); 

回答by Hristo

Check out Date.js. Its really neat!

查看 Date.js。它真的很整洁!

http://www.datejs.com/

http://www.datejs.com/

Here are a couple of ways to do it using Date.js:

以下是使用 Date.js 的几种方法:

// today - 7 days
// toString() is just to print it to the console all pretty

Date.parse("t - 7 d").toString("MM-dd-yyyy");     // outputs "12-06-2011"
Date.today().addDays(-7).toString("MM-dd-yyyy");  // outputs "12-06-2011"
Date.today().addWeeks(-1).toString("MM-dd-yyyy"); // outputs "12-06-2011"

As an unrelated side note, do check out Moment.js as well... I think the 2 libraries compliment each other :)

作为一个不相关的旁注,也请查看 Moment.js ......我认为这两个库相互补充:)

http://momentjs.com/

http://momentjs.com/