I need to render a subscription date range on a page like this:
31 May 2023 — 30 June 2023
When user subscribes then backend sends a subscription start date (it never changes and always the same). For example if user subscribed on 31 May 2023 then the start date will be:
const startDate = "2023-05-31T10:16:14+00:00"
Then there’re nextDates
when a new credits will be added to user account
const nextDate = "2023-06-30T10:16:20.404358+00:00",
const nextDate1 = "2023-07-31T10:16:20.404358+00:00",
const nextDate2 = "2023-08-31T10:16:20.404358+00:00",
So my question is how can I get the start date for each nextDate
?
The output should be like this:
const startDate = "2023-05-31T10:16:14+00:00"
const nextDate = "2023-06-30T10:16:20.404358+00:00" // startDate should be 31 May 2023
const nextDate1 = "2023-07-31T10:16:20.404358+00:00" // startDate should be 30 June 2023
I tried this but the output is incorrect:
const getPreviousInterval = (nextDate, months) => {
const date = new Date(nextDate);
const dateMonthsAgoUnix = date.setMonth(date.getMonth() - months);
return new Date(dateMonthsAgoUnix);
};
getPreviousInterval("2023-06-30T10:16:20.404358+00:00", 1);
// incorrect output is 2023-05-30T10:16:20.404Z
// correct output is 2023-05-31T10:16:14+00:00
4
Answers
Seems like you want the last day of the previous calendar month rather than something "one month ago". See details of setDate(0) here.
You can try to build a list of future dates by adding a month to the date and then one day in milliseconds each time.
You can then use the
Intl.DateTimeFormat
class to format the date in British format.