从当前日期减去1周 - javascript

时间:2013-11-13 15:12:05

标签: javascript

这就是我获取当前日期,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;

5 个答案:

答案 0 :(得分:3)

使用moment.js,给定

moment().calendar();

Today at 10:27 AM

然后您需要的只是

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

成为

06-Nov-2013

答案 1 :(得分:2)

您可以尝试这样: -

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");

答案 2 :(得分:1)

只需在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 example

答案 3 :(得分:0)

Moment.js对于像这样的相对约会对象很棒:

var one_week_ago = moment().subtract('weeks', 1).format('DD-MMM-YYYY')

答案 4 :(得分: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。