MATLAB - Dates and Time
Modern Date and Time Handling in MATLAB
Section titled “Modern Date and Time Handling in MATLAB”Effective handling of date and time information is crucial for data analysis, scheduling, and logging. Modern MATLAB provides a powerful and intuitive object-oriented framework for these tasks, centered around the datetime, duration, and calendarDuration data types.
Best Practice: Avoid legacy functions like now, datenum, and date. The datetime object is the standard for all new code as it is more robust, feature-rich, and integrates seamlessly with other MATLAB functionalities like plotting and tables.
The datetime Object: The Core of Time
Section titled “The datetime Object: The Core of Time”A datetime object represents a specific point in time (a timestamp). You can create them in several ways:
% Get the current date and timet_now = datetime('now');
% Create a datetime from specific componentst_specific = datetime(2025, 10, 31, 18, 30, 0); % Y, M, D, H, MI, S
% Parse a date string with a specific formatt_from_string = datetime('2024-07-04', 'InputFormat', 'yyyy-MM-dd');
% Create an array of datetimest_array = [datetime('today'); datetime('tomorrow')];Working with Time Zones
Section titled “Working with Time Zones”A key feature of datetime is its awareness of time zones. This is critical for avoiding ambiguity.
% Create a datetime object with your local time zonet_local = datetime('now', 'TimeZone', 'local');disp(t_local);
% Convert to another time zonet_tokyo = t_local;t_tokyo.TimeZone = 'Asia/Tokyo';disp(t_tokyo);
% Creating a time-zoned object directlyt_ny = datetime(2024, 1, 1, 9, 0, 0, 'TimeZone', 'America/New_York');Arithmetic: duration and calendarDuration
Section titled “Arithmetic: duration and calendarDuration”MATLAB provides two types for time differences, and understanding their distinction is key:
duration: Represents an exact, fixed length of time (e.g., 24 hours). Usehours(),minutes(),seconds().calendarDuration: Represents calendar-based lengths of time (e.g., 1 day, 1 month), which can vary in length (e.g., due to daylight saving or the number of days in a month). Usecaldays(),calmonths(),calyears().
Example: The Difference in Action
Section titled “Example: The Difference in Action”% Let's use a date when daylight saving time starts in the USstartTime = datetime(2024, 3, 10, 1, 30, 0, 'TimeZone', 'America/New_York');
% Adding exactly 24 hours (a duration)endTime_duration = startTime + hours(24);disp(endTime_duration); % Output: 11-Mar-2024 02:30:00 (The clock jumped from 2 to 3 AM)
% Adding one calendar day (a calendarDuration)endTime_calday = startTime + caldays(1);disp(endTime_calday); % Output: 11-Mar-2024 01:30:00 (Preserves the time of day)Common Arithmetic Operations
Section titled “Common Arithmetic Operations”t1 = datetime('now');
% Add 5 days and 10 hourst2 = t1 + caldays(5) + hours(10);
% Create a sequence of datetimes every 6 hours for the next 48 hourst_sequence = t1 + hours(0:6:48);
% Calculate the time difference between two datetimesdiff = datetime('now') - t1; % Result is a duration objectFormatting and Display
Section titled “Formatting and Display”You can easily control how datetime objects are displayed using the Format property.
t = datetime('now');
t.Format = 'dd-MMM-yyyy HH:mm:ss';disp(t); % e.g., 30-Aug-2024 15:45:10
t.Format = 'eeee, MMMM d, yyyy';disp(t); % e.g., Friday, August 30, 2024
t.Format = 'uuuu-MM-dd''T''HH:mm:ssZ'; % ISO 8601 formatdisp(t);Practical Application: Plotting Time-Series Data
Section titled “Practical Application: Plotting Time-Series Data”datetime objects integrate directly with plotting functions, automatically creating meaningful axis labels.
% 1. Create time-series datastartTime = datetime('today');timePoints = startTime + hours(0:72); % 3 days of hourly data
% 2. Generate some sample data (e.g., temperature)tempData = 20 + 5 * sin(2*pi*(0:72)/24) + randn(1, 73);
% 3. Plot the datafigure;plot(timePoints, tempData, '-o');
title('Simulated Temperature over 3 Days');xlabel('Date and Time');ylabel('Temperature (°C)');grid on;Useful Utility Functions
Section titled “Useful Utility Functions”dateshift: Shifts datetime values to the start or end of a specified unit (e.g., ‘month’, ‘year’, ‘dayofweek’).dateshift(t, 'start', 'month')finds the first day of the month for datetimet.calendar: Displays a simple text-based calendar in the command window.calendar(2025, 12)shows the calendar for December 2025.isbetween: Checks if a datetime is within a specified interval.isbetween(t, t_start, t_end).