Atish
Atish

Reputation: 174

subtract 1 week from current date - javascript

This is how I am getting current date, dd-MMM-yyyy format. How do I subtract 1 week.

    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;

Upvotes: 7

Views: 21392

Answers (6)

Using date-fns,

import { format, subDays } from 'date-fns';

console.log(format(subDays(new Date(),7), 'dd-MMM-yyyy')); // 18-Oct-2023

Upvotes: -1

Gabriel Borges
Gabriel Borges

Reputation: 163

In order to sum or subtract from the date's elements, all you need to do is:

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())

The great thing about it is that even if the numbers are not "valid" for each parameter, the method will adjust it correctly, for example, if the number of the month is 13, another year will be added to the date and the month will be 1.

Upvotes: 1

arturomp
arturomp

Reputation: 29580

With moment.js, given that

moment().calendar();

is

Today at 10:27 AM

then all you need is

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

which becomes

06-Nov-2013

Upvotes: 3

codenamev
codenamev

Reputation: 2208

Moment.js is awesome for relative date stuff like this:

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

Upvotes: 0

j08691
j08691

Reputation: 207891

Just add d.setDate(d.getDate() - 7); after your 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

Upvotes: 8

Rahul Tripathi
Rahul Tripathi

Reputation: 172398

You may try like this:-

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

Using Date.js you can do like this:

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

Upvotes: 5

Related Questions