Dates and Time in MATLAB
Last Updated :
11 Oct, 2022
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
datetime
datetime(YEAR, MONTH, DATE)
datetime(YEAR, MONTH, DAY, HOUR, MINUTE, SECOND)
|
Output:
MATLAB also allows users to create DateTime arrays from vectors.
Example 2:
Matlab
year = [2013, 2023];
month = [1,3];
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
calyears(1:2)
calquarters(1)
calmonths(1:5)
|
Output:
We can perform operations on DateTime arrays and calendar duration arrays.
Example 4:
Matlab
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
years(1:5)
days(1:2)
milliseconds(1:7)
|
Output:
We can also perform operations on these arrays.
Example 6:
Matlab
h = hours(1:5)
dt = datetime( "today" )
dt - h
|
Output:
Share your thoughts in the comments
Please Login to comment...