0

I have start and end dates in my component which I am getting using moment library through the time picker.

So suppose my datepicker selects startDate and endDate for the today. Now I need another dates let's say previousStartDate and previousEndDate which should be the same time difference compared to startDate and endDate.

startDate = '20-06-2019 00:00:00'
endDate = '20-06-2019 23:59:59'

So the previousStartDate and previousEndDate should be

previousStartDate = '19-06-2019 00:00:00'
previousEndDate = '19-06-2019 23:59:59'

How can do that?

I have tried this but with no success

  getPreviousStartDates ({ startDate, endDate }) {
     const diff = endDate.diff(startDate)
     const diffDuration = moment.duration(diff)
     const subtractStartDate = startDate.subtract(diff)
     console.log({subtractStartDate})
     return subtractStartDate
  }

Some more clarification

Suppose The time difference between the startDate and endDate is 3 days (17-6-2019 00:00:00 && 19-6-2019 23:59:59) then the time difference between previousStartDate and previousEndDate should be the same but past 3 days. (14-6-2019 00:00:00 && 16-6-2019 23:59:59)

Profer
  • 553
  • 8
  • 40
  • 81
  • Why don't you just return both dates (`startDate` and `endDate`) minus 1 day ? – BJRINT Jun 20 '19 at 09:59
  • [this](https://stackoverflow.com/questions/24428656/subtract-time-from-date-moment-js) should answer your question – FunkeyFlo Jun 20 '19 at 10:11
  • 1
    There is some information missing here... Can you explain precisely how you want previousStartDate and previousEndDate to be computed? – Keilath Jun 20 '19 at 10:11
  • @BJRINT `startDate` and `endDate` can be changed. What ever the difference I get from the timepicker I need to subtract same from the `previousStartDate` and `previousEndDate` – Profer Jun 20 '19 at 10:15
  • @Keilath Suppose The time difference between the `startDate` and `endDate` is 3 days `(17-6-2019 00:00:00 && 19-6-2019 23:59:59)` then the time difference between `previousStartDate` and `previousEndDate` should be the same but past 3 days. `(14-6-2019 00:00:00 && 16-6-2019 23:59:59)` – Profer Jun 20 '19 at 10:20

1 Answers1

1

Is it a requirement that it is done using momentjs? I'm not so familiar with momentjs, but you could do it in javascript like this:

let start = new Date("2019-06-20 00:00:00");
let end = new Date("2019-06-20 23:59:59");
let duration = end.getTime() - start.getTime(); // milliseconds

let prevStart = new Date(start.getTime() - duration);
let prevEnd = new Date(prevStart.getTime() + duration);
tmadsen
  • 941
  • 7
  • 14
  • *I'm not so familiar with momentjs* No problem Thank you for the answer. I will check and accept it. – Profer Jun 20 '19 at 12:08