3

这就是我获取当前日期的方式,dd-MMM-yyyy 格式。我如何减去 1 周。

    var m_names = new Array("JAN", "FEB", "MAR",
            "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC");

    var d = new Date();
    var curr_date = d.getDate();
    var curr_month = d.getMonth();
    var curr_year = d.getFullYear();
    var current = curr_date + "-" + m_names[curr_month] + "-" + curr_year;
4

5 回答 5

5

只需d.setDate(d.getDate() - 7);在您的后面添加var d = new Date();

 var m_names = new Array("JAN", "FEB", "MAR",
     "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC");
 var d = new Date();
 d.setDate(d.getDate() - 7);
 var curr_date = d.getDate();
 var curr_month = d.getMonth();
 var curr_year = d.getFullYear();
 var current = curr_date + "-" + m_names[curr_month] + "-" + curr_year;

jsFiddle 示例

于 2013-11-13T15:18:06.617 回答
3

你可以这样尝试:-

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

使用Date.js你可以这样做:

Date.parse("t - 7 d").toString("MM-dd-yyyy");     
Date.today().addDays(-7).toString("MM-dd-yyyy");  
Date.today().addWeeks(-1).toString("MM-dd-yyyy");
于 2013-11-13T15:14:03.793 回答
3

有了moment.js,鉴于

moment().calendar();

Today at 10:27 AM

那么你所需要的就是

moment().subtract('days', 7).format('DD-MMM-YYYY')

变成

06-Nov-2013
于 2013-11-13T15:34:57.390 回答
0

Moment.js非常适合这样的相对日期:

var one_week_ago = moment().subtract('weeks', 1).format('DD-MMM-YYYY')
于 2013-11-13T15:36:35.023 回答
0

为了从日期的元素中求和或减去,您需要做的就是:

let currentDate = new Date()
//get each element from the current date
let year = currentDate.getFullYear()
let month = currentDate.getMonth()
let day = currentDate.getDate()
let hours = currentDate.getHours()
let minutes = currentDate.getMinutes()
let seconds = currentDate.getSeconds()
let milliseconds = currentDate.getMilliseconds()


//build the new date according the changes you want to do
let newDate = new Date(year, month, day - 7, hours, minutes, seconds, milliseconds )
console.log(newDate.toISOString())

它的伟大之处在于,即使每个参数的数字不是“有效”的,该方法也会正确调整它,例如,如果月份的数字是 13,则会在日期和月份中添加另一个年份将是 1。

于 2020-04-11T20:25:40.440 回答