简体   繁体   中英

How to get previous week particular day from given date?

From the backend, I get the date of the array with this format "18/11 Wednesday", "19/11 Thursday",... Then I store this in an array in the frontend.

const sevenDays = [];

getData() {

  sevenDays.push(this.sales[x].values[i].date);

}

Now I need to get a particular day of last week from all the elements In this array. As an example,

sevenDays[0] = "18/11 Wednesday"

Output should be

newsevenDays[0] = "11/11 Wednesday"

Please give me help guys, I tried so many times.

To get the date 7 days before a date, you can use the subtract method of the moment.js package (docs below), but you need to get your dates in a right format before and insert it as a parameter of moment()

moment(new Date()).subtract(7, 'days').format('DD/MM/YYYY')
---> will return you the date of 7 days ago, with format DD/MM/YYYY

Docs: https://momentjscom.readthedocs.io/en/latest/moment/03-manipulating/02-subtract/

You can use native javascript function Date() without using moment.js

var arbitraryDate = new Date();
arbitraryDate.setDate(arbitraryDate.getDate()-5)

to see output in MM/DD/YYYY format.

arbitraryDate.toLocaleDateString()

Try running the code below

 var arbitraryDate = new Date(); arbitraryDate.setDate(arbitraryDate.getDate()-5) foo = arbitraryDate.toLocaleDateString() document.getElementById('arbitrary').innerHTML = foo
 <h4 id="arbitrary"></h4>

I found the answer and I hope this should help if someone faces this kind of problem. The moment.js gives any custom format of the date convert into a standard format. So here first I give my custom format as a second parameter 'DD/MM dddd' in moment() function. Then you can give your final formats as well.

 finalDate = moment('18/11 Wednesday', 'DD/MM dddd').subtract(7,'days').format('DD/MM dddd');

output:

finalDate = 11/11 Wednesday

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM