Generate a date in nodejs between to dates and a weekday number

46 Views Asked by At

I have a calendar where users can add events and choose if the event should be recurring. When loading the calendar afterwards, I have a startdate and and enddate that the calendar shows (typically a hole week). In my database I have a list of events that I loop through and find the ones that are recurring. All these events have a startdate and enddate ex:

starttime 2024-01-17T05:00:00.000+00:00 
endtime 2024-01-17T06:00:00.000+00:00

As I paginate my calendar out in the future, I would like to add the events to the view, based on the starttime (hours) and endtime (hours). But to do so, I need a way to add these events to the current timeframe that the calendar shows. Actually set a new date for them in the future.

I have tried something like this:

var weekday = moment(ClassesAndEvents[i].starttime).weekday();
var newDate = moment(startdate).add(weekday, 'd').toDate();

Where startdate is the currently first date the calendar shows, but it ends up showing the ClassesAndEvents[i].starttime - one day.

Updated with some more explanation:

Lets say a user creates an event that should be recurring. This event gets this start time: 2024-01-17T05:00:00.000+00:00 and are saved in my database. The 17. of January is a Wednesday. When viewing the calendar for ex. the first week in February, I need to show this event on Wednesday as well with the same start time. So I need a way to generate a new start time for the event so people can sign up for that event in the future. When viewing the calendar I have a start and end date (Sunday through Monday), so how can I best find out what date the Wednesday in the first week of February is, based on the start date of that week and the end date (Sunday and Monday). I hope it makes more sense.

Solution: Figured it out, it can be done like this:

//First get the weeknumber by adding the start of the week:

const someday = moment('2024-02-17T05:00:00.000+00:00').week();

//Then Find out what date ex. monday is in that week:

const futuredate = moment().day("Monday").week(someday);
0

There are 0 best solutions below