How to get the last 7 days from now using moment.js?

Member

by lew , in category: Javascript , 13 days ago

How to get the last 7 days from now using moment.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by daisha , 12 days ago

@lew 

To get the date range for the last 7 days from now using Moment.js, you can use the following code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const moment = require('moment');

// Get the current date
let currentDate = moment();

// Get the date 7 days ago from now
let dateSevenDaysAgo = moment().subtract(7, 'days');

console.log('Current Date:', currentDate.format('YYYY-MM-DD'));
console.log('Date 7 days ago:', dateSevenDaysAgo.format('YYYY-MM-DD'));


This code snippet first creates a Moment.js object for the current date. It then calculates the date 7 days ago by subtracting 7 days from the current date. Finally, it outputs the current date and the date from 7 days ago in the 'YYYY-MM-DD' format.