Skip to content

MATLAB - Dates and Time

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.

A datetime object represents a specific point in time (a timestamp). You can create them in several ways:

% Get the current date and time
t_now = datetime('now');
% Create a datetime from specific components
t_specific = datetime(2025, 10, 31, 18, 30, 0); % Y, M, D, H, MI, S
% Parse a date string with a specific format
t_from_string = datetime('2024-07-04', 'InputFormat', 'yyyy-MM-dd');
% Create an array of datetimes
t_array = [datetime('today'); datetime('tomorrow')];

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 zone
t_local = datetime('now', 'TimeZone', 'local');
disp(t_local);
% Convert to another time zone
t_tokyo = t_local;
t_tokyo.TimeZone = 'Asia/Tokyo';
disp(t_tokyo);
% Creating a time-zoned object directly
t_ny = datetime(2024, 1, 1, 9, 0, 0, 'TimeZone', 'America/New_York');

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). Use hours(), 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). Use caldays(), calmonths(), calyears().
% Let's use a date when daylight saving time starts in the US
startTime = 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)
t1 = datetime('now');
% Add 5 days and 10 hours
t2 = t1 + caldays(5) + hours(10);
% Create a sequence of datetimes every 6 hours for the next 48 hours
t_sequence = t1 + hours(0:6:48);
% Calculate the time difference between two datetimes
diff = datetime('now') - t1; % Result is a duration object

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 format
disp(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 data
startTime = 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 data
figure;
plot(timePoints, tempData, '-o');
title('Simulated Temperature over 3 Days');
xlabel('Date and Time');
ylabel('Temperature (°C)');
grid on;
  • 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 datetime t.
  • 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).