Home > database >  unable to get previous date using moment.js
unable to get previous date using moment.js

Time:03-03

I have the following date

let api_date = '2022-03-01T00:00:00.000Z'

Now, i want to get previous 2 dates starting from api_date. Basically now i need dates as 2022-02-28T00:00:00.000Z and 2022-02-27T00:00:00.000Z Basically for api_date of 1st March, i need previous 2 dates as Feb 28th and Feb 27th.

I tried using this below code

let t-1 = moment().substract(1, 'days')
let t-2 = moment().subtract(2, 'days')

But this only provides previous 2 dates from the present date. i.e. present date is 2nd March, so it provides previous 2 dates based of 2nd March.

how can i use moment to get my current specified date and get previous 2 dates based on that. Any advice to achieve that ? i saw the documentation of moment.js too but i didnt find a definitive answer.

CodePudding user response:

You were almost there, you need to pass your date to moment. Otherwise it defaults to current date ( as you found out ).

let t-1 =  moment(api_date).subtract(1, 'days')
let t-2 =  moment(api_date).subtract(2, 'days')

CodePudding user response:

You should create a date object from the date you wanna parse like this,

let api_date = '2022-03-01T00:00:00.000Z'
var dateObj = new Date(api_date);

then you can create a moment object based on the date object just like this,

var momentObj = moment(dateObj);

then if you perfom your specific logic you will get your desired result, like this

 let date1 = momentObj.substract(1, 'days')
 let date2 = momentObj.substract(2, 'days')
  • Related