How Can I Increment Dates in Matlab?

Written by michael carroll

Share

Tweet

Share

Email

A date is stored and manipulated in MATLAB as a string, in a vector, or as a single number. MATLAB provides convenient functions to convert between these formats, and also includes a function to increment a date by the time unit you specify. Use the "addtodate" function to increment a date in MATLAB, nesting the "datenum" function as necessary to convert the date before it's incremented.

Skill level:

Easy

Other People Are Reading

Instructions

1

Type the following command into MATLAB's Command Window to increment the current date by one month:

addtodate(now,1,'month')

The first argument is the date to increment ("now" returns the current date as a number). The second argument is the number to increment by. The third argument is the unit of time to increment by. The result is returned as a single number. To convert a date number to a readable string, pass it to the "datestr" function.

2

Use any one of the following keywords as the third argument of the "addtodate" function to increment a date by a specific amount: 'year', 'month', 'day', 'hour', 'minute', 'second', or 'millisecond'.

3

Use the "datenum" function to convert any MATLAB date to the format required by "addtodate:"

addtodate(datenum('10-Jul-2011'),1,'day')

In this case, a date represented as a string is passed to "datenum" before being passed to "addtodate." Pass any date variable to "datenum" to ensure that "addtodate" will work properly.