addtodate

Adds a number of calendar units, such as months or days, to a date number.

Category: Language Fundamentals > Data Types

Syntax

d2 = addtodate(d, q, f)

Adds q units of type f to the serial date d.

Description

Years and months are calendar units of unequal length, so adding them is not the same as adding a fixed number of days. If the resulting day does not exist, it is moved to the last day of the month: one month after January 31 is February 29 in 2024. Units from 'week' down are plain multiples of a day.

Input arguments

d
Serial date number, as from datenum.
q
Quantity to add; may be negative.
f
Unit: 'year', 'month', 'week', 'day', 'hour', 'minute', 'second' or 'millisecond'.

Output arguments

d2
Serial date number after the addition.

Example

End-of-month clamping

d = datenum(2024, 1, 31);
disp(datestr(addtodate(d, 1, 'month'), 'yyyy-mm-dd'))
disp(datestr(addtodate(d, 1, 'year'), 'yyyy-mm-dd'))
disp(addtodate(d, 1, 'week') - d)
Output
2024-02-29
2025-01-31
     7

See also

datenum datestr calendarDuration caldays datetime