Skip to content
Advertisement

Can I add number of days to the (dayoftheweek) to get another day?

I have a date and from that I find the dayoftheweek . Lets say the day I found is Tuesday . I have a variable that has duration . Lets say the duration is 5 days . Will I be able to add 5 to Tuesday and get Saturday as the answer . Tuesday should be considered as day 1 and saturday as day 5.

date = 04/13/2021                         #in mm/dd/yyyy
dayoftheweek = GetDayOfWeek(date)         #Tuesday
duration = 5

Is this correct?

finaldayoftheweek = dayoftheweek + 5        # I want to get Saturday as answer

If not how do I do that ?

Advertisement

Answer

If you want Saturday, add 4 days.

/*
 * Obtain the day of the week, tht will occur a number of days after the
 * provided {@code dateString}.<p>
 * @param  {String} dateString - format: mm/dd/yyyy
 * @param  {Numer}  addDays    - days to add to date
 * @return {String} returns the day of week in its 'long' format.
 */
const getDayOfWeek = (dateString, addDays) => {
  const [month, date, year] = dateString.split('/').map(v => parseInt(v, 10));
  const d = new Date(year, month - 1, date);
  d.setDate(d.getDate() + addDays);
  return d.toLocaleDateString('en-US', { weekday: 'long' });
}

console.log(getDayOfWeek('04/13/2021', 4)); // Saturday

If all you want to do is add a number of days to a day of week and get another day of week then use a modulo operation.

#!/usr/bin/env python3
DAYS_IN_A_WEEK = 7

start_day_of_week = 2 # Tuesday
number_of_days_to_add = 10 # or 3, 17, 24, 31, etc...
end_day_of_week = (start_day_of_week + number_of_days_to_add) % DAYS_IN_A_WEEK

print(end_day_of_week) # 5 (Saturday)
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement