Extract or Assign Date and Time Components of Datetime
Array
This example shows two ways to extract date and time components from existing datetime arrays:
accessing the array properties or calling a function. Then, the example shows how to modify the date
and time components by modifying the array properties.
Access Properties to Retrieve Date and Time Component
Create a datetime array.
t = datetime('now') + calyears(0:2) + calmonths(0:2) + hours(20:20:60)
t = 1x3 datetime
02-Sep-2021 10:44:38
03-Oct-2022 06:44:38
04-Nov-2023 02:44:38
Get the year values of each datetime in the array. Use dot notation to access the Year property of t.
t_years = t.Year
t_years = 1×3
2021
2022
2023
The output, t_years, is a numeric array.
Get the month values of each datetime in t by accessing the Month property.
t_months = t.Month
t_months = 1×3
9
10
11
You can retrieve the day, hour, minute, and second components of each datetime in t by accessing the
Hour, Minute, and Second properties, respectively.
Use Functions to Retrieve Date and Time Component
Use the month function to get the month number for each datetime in t. Using functions is an
alternate way to retrieve specific date or time components of t.
m = month(t)
m = 1×3
9
10
11
Use the month function rather than the Month property to get the full month names of each datetime
in t.
m = month(t,'name')
Extract or Assign Date and Time Components of Datetime Array
7-23
Array
This example shows two ways to extract date and time components from existing datetime arrays:
accessing the array properties or calling a function. Then, the example shows how to modify the date
and time components by modifying the array properties.
Access Properties to Retrieve Date and Time Component
Create a datetime array.
t = datetime('now') + calyears(0:2) + calmonths(0:2) + hours(20:20:60)
t = 1x3 datetime
02-Sep-2021 10:44:38
03-Oct-2022 06:44:38
04-Nov-2023 02:44:38
Get the year values of each datetime in the array. Use dot notation to access the Year property of t.
t_years = t.Year
t_years = 1×3
2021
2022
2023
The output, t_years, is a numeric array.
Get the month values of each datetime in t by accessing the Month property.
t_months = t.Month
t_months = 1×3
9
10
11
You can retrieve the day, hour, minute, and second components of each datetime in t by accessing the
Hour, Minute, and Second properties, respectively.
Use Functions to Retrieve Date and Time Component
Use the month function to get the month number for each datetime in t. Using functions is an
alternate way to retrieve specific date or time components of t.
m = month(t)
m = 1×3
9
10
11
Use the month function rather than the Month property to get the full month names of each datetime
in t.
m = month(t,'name')
Extract or Assign Date and Time Components of Datetime Array
7-23
