使用jQuery/Javascript获取上周日期 [英] Get last week date with jQuery/Javascript
问题描述
我正在尝试在javascript中获取上个星期的日期,而没有时间.
I'm trying to get the last week date in javascript, without the time.
例如,2012年10月2日,而不是格林尼治标准时间10-02-12 13:34:56.
So for example, 10-02-2012, instead of 10-02-12 13:34:56 GMT.
为此有一个简单的解决方案吗?
Is there an easy solution out there for this?
谢谢!
我正在尝试使它动态化,以使结果变量始终在当前日期之前一周.如果有帮助或可以使用的话,这就是我今天计算出的变量!
I'm trying to make this dynamic, so that the resulting variable is always one week before the current date. Here's what I've done to calculate the today variable, if this helps or can be used!
var currentTime = new Date();
var month = currentTime.getMonth() + 1
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var today = month + "-" + day + "-" + year;
alert(today)
推荐答案
我喜欢这样的东西
I prefer something like this
function getLastWeek() {
var today = new Date();
var lastWeek = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 7);
return lastWeek;
}
var lastWeek = getLastWeek();
var lastWeekMonth = lastWeek.getMonth() + 1;
var lastWeekDay = lastWeek.getDate();
var lastWeekYear = lastWeek.getFullYear();
var lastWeekDisplay = lastWeekMonth + "/" + lastWeekDay + "/" + lastWeekYear;
var lastWeekDisplayPadded = ("00" + lastWeekMonth.toString()).slice(-2) + "/" + ("00" + lastWeekDay.toString()).slice(-2) + "/" + ("0000" + lastWeekYear.toString()).slice(-4);
console.log(lastWeekDisplay);
console.log(lastWeekDisplayPadded);
如果您使用的是jQuery UI,则可以执行此操作,而不必执行手动操作来构建字符串
And if you're using jQuery UI, you can do this instead of the manual steps to build the string
var lastWeekDisplay = $.datepicker.formatDate('mm/dd/yy', getLastWeek());
或者今天
var todayDisplay = $.datepicker.formatDate('mm/dd/yy', new Date());
这篇关于使用jQuery/Javascript获取上周日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!