How to use the addDays function from date-fns

Find comprehensive JavaScript date-fns.addDays code examples handpicked from public code repositorys.

date-fns.addDays is a function that adds a specified number of days to a given date.

97
98
99
100
101
102
103
104
105
106
const startOfWeek = datefns.startOfWeek(new Date(), { locale });
const startIndex = datefns.getDay(startOfWeek);
const weekdays = [];

for (let i = 0; i < 7; i += 1) {
  const weekday = datefns.addDays(startOfWeek, i);

  weekdays.push(
    datefns.format(weekday, 'EEE', { locale }),
  );
fork icon28
star icon313
watch icon7

+ 7 other calls in file

71
72
73
74
75
76
77
78
79
80
81
const getAppointmentStartTime = (
  eligibility = 'ELIGIBLE',
  preCheckInValid = false,
  uuid = defaultUUID,
) => {
  let startTime = preCheckInValid ? dateFns.addDays(new Date(), 1) : new Date();


  if (eligibility === 'INELIGIBLE_TOO_LATE') {
    startTime = dateFns.subHours(startTime, 1);
  } else if (eligibility === 'INELIGIBLE_TOO_EARLY') {
fork icon124
star icon219
watch icon0

How does date-fns.addDays work?

date-fns.addDays is a function that takes in a date and a number of days to add, and returns a new Date object that is the specified number of days added to the original date. The function first checks if the input date is valid, and then creates a new date object with the same value as the input date. It then uses the built-in Date object's setDate() method to add the specified number of days to the new date object. Finally, it returns the new date object.

130
131
132
133
134
135
136
137
138
139
case 'm':
        return dateTime.addMinutes(date, timeLength);
case 'h':
        return dateTime.addHours(date, timeLength);
case 'd':
        return dateTime.addDays(date, timeLength);
case 'w':
        return dateTime.addWeeks(date, timeLength);
case 'M':
        return dateTime.addMonths(date, timeLength);
fork icon55
star icon190
watch icon27

51
52
53
54
55
56
57
58
59
60
function getWeekDaysFrom(startDate, number = 5) {
    if (!(startDate instanceof Date)) startDate = getDateFromTick(startDate);

    const days = [];
    for (let i = 0; i < number; i++) {
        let date = addDays(startDate, i);
        days.push([
            getDayName(date),
            formatDate(toDate(date)),
            date
fork icon9
star icon13
watch icon4

Ai Example

1
2
3
4
5
6
7
8
const { addDays } = require("date-fns");

const date = new Date("2022-03-31");
const daysToAdd = 7;
const newDate = addDays(date, daysToAdd);

console.log(newDate);
// Output: 2022-04-07T00:00:00.000Z

In this example, date-fns's addDays function is used to add daysToAdd number of days to date. The resulting new date is then logged to the console.

74
75
76
77
78
79
80
81
82
83
const dateFns = require('date-fns');

let aWeekLater = dateFns.addDays(new Date(), 7);
console.log(`Date after a week is ${aWeekLater.toDateString()}`);

const aWeekAfter1Jan2022 = dateFns.addDays(new Date('2022-01-01'),  7);
console.log(`Date after a week of 2022-01-01 is ${aWeekAfter1Jan2022.toDateString()}`);
```

When the above script is run with `node date-fns.js` it will give the exact same output as the above example which looks like this:
fork icon9
star icon10
watch icon4

357
358
359
360
361
362
363
364
365
366
//Create token
const cohort = await CohortModel.findOne({ name: sessionPhase1.cohort });
if (!cohort) return res.status(404).send({ ok: false, code: ERRORS.NOT_FOUND });

const startAt = datefns.subDays(new Date(cohort.dateStart), 7);
const endDate = datefns.addDays(new Date(cohort.dateEnd), 7);

const sessionToken = await sessionPhase1TokenModel.create({
  token: crypto.randomBytes(50).toString("hex"),
  startAt: startAt,
fork icon4
star icon8
watch icon4

+ 24 other calls in file

39
40
41
42
43
44
45
46
47
48
            matches.forEach(match => {
                allDayScores[index].score += match.dataValues.score;
            });
        }
            
        currentDate = addDays(currentDate, 1);
    }

    return allDayScores;
}
fork icon3
star icon3
watch icon1

70
71
72
73
74
75
76
77
78
async function dailyRoutine(linkySession, gotifyClient, usagePointId) {
  // Determining min days

  let minDay = subDays(startOfToday(), SEEK_DAYS);
  minDay = dateMax([minDay, (await store.getLastDay(usagePointId)) || minDay]);
  minDay = addDays(minDay, 1);

  // Retrieving prices 
  const prices = await store.getPrices();
fork icon0
star icon3
watch icon2

44
45
46
47
48
49
50
51
52
53
54


function createNodeObject(title) {
    return {
        title: title,
        uuid: uuid(),
        dueDate: dateFns.addDays(dateFns.addHours(dateFns.startOfDay(new Date()), 18), 7),
        priorityLevel: "H",
        projectManager: "You",
        collapseNode: false,
        complete: false,
fork icon0
star icon2
watch icon1

20
21
22
23
24
25
26
27
28
29
    }
    return new Date(v)
  }
}

exports.addDaysImpl = dateFns.addDays
exports.addHoursImpl = dateFns.addHours
exports.addISOYearsImpl = dateFns.addISOYears
exports.addMillisecondsImpl = dateFns.addMilliseconds
exports.addMinutesImpl = dateFns.addMinutes
fork icon0
star icon2
watch icon1

+ 16 other calls in file

55
56
57
58
59
60
61
62
63
// sleep(1000).then(() => {
    let y = datefns.getYear(d)
    let m = datefns.getMonth(d)+1
    let day = datefns.getDate(d)

    let nextDay = datefns.addDays(d, 1)
    let y2 = datefns.getYear(nextDay)
    let m2 = datefns.getMonth(nextDay)+1
    let day2 = datefns.getDate(nextDay)
fork icon0
star icon2
watch icon2

23
24
25
26
27
28
29
30
31
})

const timelineData = []
const GAP = 5
const firstArticleDate = new Date(data[0].createdAt)
const fromDate = addDays(firstArticleDate, -GAP)
const toDate = addDays(new Date(data[data.length - 1].createdAt), GAP)

let top = true
fork icon0
star icon1
watch icon0

+ 5 other calls in file

2
3
4
5
6
7
8
9
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

module.exports = (today = new Date()) => {
  const start = startOfWeek(today, { weekStartsOn: 6 });
  const satDisplay = `${months[start.getMonth()]} ${start.getDate()}`;
  const sun = addDays(start, 1);
  return `${satDisplay}/${sun.getDate()}`;
};
fork icon0
star icon1
watch icon2

48
49
50
51
52
53
54
55
56
57
    this.state.weekStartDate,
    'yyyy-MM-dd',
    { awareOfUnicodeTokens: true }
  ), 
  dateFns.format(
    dateFns.addDays(this.state.weekStartDate,7),
    'yyyy-MM-dd',
    { awareOfUnicodeTokens: true }
  ),
)
fork icon2
star icon0
watch icon3

+ 5 other calls in file

120
121
122
123
124
125
126
127
128
129
const newInv = {
    user: req.user._id,
    email: req.user.email,
    ...plan,
    capital: req.body.capital,
    expiry: addDays(new Date(), plan.duration),
};
await CLUSTER.create(newInv)
await USER.updateOne({ _id: req.user._id }, {
    $inc: { balance: -Number(req.body.capital) },
fork icon0
star icon0
watch icon1

+ 23 other calls in file

1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
  start_date = format(new Date(start_date), config.validate.DATE_FORMAT);
  end_date = format(new Date(end_date), config.validate.DATE_FORMAT);
  const dates = [];
  while (start_date <= end_date) {
    dates.push({ start: start_date, end: start_date });
    let nextDayDate = addDays(new Date(start_date), 1);
    start_date = format(new Date(nextDayDate), config.validate.DATE_FORMAT);
  }
  return dates;
}
fork icon0
star icon0
watch icon1

+ 22 other calls in file

210
211
212
213
214
215
216
217
218
219
  $push: {
    bids: {
      auctionId,
      amount,
      duration,
      expireOn: addDays(new Date(), duration),
    },
  },
},
null,
fork icon0
star icon0
watch icon0

+ 11 other calls in file

62
63
64
65
66
67
68
69
70
71
    break;
case 'h':
    remindTime = addHours(now, parseInt(time.slice(0, -1)));
    break;
case 'd':
    remindTime = addDays(now, parseInt(time.slice(0, -1)));
    break;
case 'w':
    remindTime = addWeeks(now, parseInt(time.slice(0, -1)));
    break;
fork icon0
star icon0
watch icon0

+ 2 other calls in file

22
23
24
25
26
27
28
29
30
31
32
33
const END = 17;
const SEGMENT = 15;
const DAYS = 5;


const START_DATE = new Date();
const END_DATE = fns.addDays(START_DATE, DAYS - 1);


const TAGS = [
  { title: "Постоянный", color: "#B0BBDB" },
  { title: "Лояльный", color: "#A8D9E0" },
fork icon0
star icon0
watch icon0

15
16
17
18
19
20
21
22
23
24
if(await isAdmin(req.user.uid)) {
    try {
        let days = [];
        let beginningDate = new Date(req.body.dateDebut)
        for (i = 0; i < req.body.nbJours; i++) {
            let date1 = addDays(beginningDate, i).setHours(8, 0, 0);
            let date2 = addDays(beginningDate, i).setHours(20, 0, 0);
            let day = new FestivalDay({
                name: "Jour " + (i + 1),
                openingTime: JSON.stringify(date1),
fork icon0
star icon0
watch icon0

Other functions in date-fns

Sorted by popularity

function icon

date-fns.format is the most popular function in date-fns (3838 examples)