MATLAB provides many ways to deal with date and time in form of DateTime, calendar duration, and duration data types. These data types do not only support storing and representing date-times but, also allow operations on date time. We shall look at these three data types separately.
DateTime
The datetime data type specifically records/represents an instant in time. For example, the datetime function alone returns the current datetime, accurate up to the second.
Datetime provides various options; let us look at them.
Example 1:
% MATLAB code for DateTime % option1 datetime % option2 datetime(YEAR, MONTH, DATE) % option3 datetime(YEAR, MONTH, DAY, HOUR, MINUTE, SECOND) |
Output:
MATLAB also allows users to create DateTime arrays from vectors.
Example 2:
% MATLAB code for create DateTime arrays from vectors % years year = [2013, 2023]; % Months month = [1,3]; % Dates date = [31, 29]; datetime(year, month, date) |
Output:
Calendar Duration:
This data type creates arrays of time elapsed in variable calendar units. This data type provides 5 functions for creating arrays of variable units.
- cal months – For creating arrays with the monthly differences in units.
- call quarters – For creating arrays with quarterly differences in units.
- calyears – For creating arrays with the yearly difference in units.
- caldays – For creating arrays with daily differences in units.
- calweeks – For creating arrays with the weekly differences in units.
Example 3:
% MATLAB Code for calendar Duration calyears(1:2) calquarters(1) calmonths(1:5) |
Output:
We can perform operations on DateTime arrays and calendar duration arrays.
Example 4:
% MATLAB code for datetime array dt = datetime(2022,11,29); c = calmonths(1:5); dt+c |
Output:
This would create a new array with these values:
The same could be done with different calendar duration arrays.
Duration:
The duration arrays are similar to calendar duration arrays with the only difference being the length of elapsed time. This data type takes fixed time units and has the following fixed functions of time length:
- years
- days
- hours
- minutes
- seconds
- milliseconds
Example 5:
% MATLAB Code for duration years(1:5) days(1:2) milliseconds(1:7) |
Output:
We can also perform operations on these arrays.
Example 6:
% MATLAB code for hours array h = hours(1:5) % date dt = datetime( "today" )
% operation dt - h |
Output: