Dates & Times
Timestamps show up in almost every data set: sensor logs, sales records, experiment schedules. MATLAB has two generations of date tools:
- Serial date numbers (
datenum,datestr,datevec, …): a date is a plaindoublecounting days. They have existed since the earliest MATLAB versions, still work in current MATLAB (marked "not recommended") and are fully supported by GNU Octave. datetime,durationandcalendarDurationobjects (MATLAB R2014b and later): proper date types with time zones, readable display and calendar-aware arithmetic. Octave 11 doesn't have them.
This lesson shows the modern types first, then does the same jobs with serial date numbers in code you can run here.
datetime in MATLAB
A datetime is created from its components, from text, or from the current clock:
% MATLAB only
d = datetime(2025, 3, 14, 15, 9, 26)
d2 = datetime('2025-07-04', 'InputFormat', 'yyyy-MM-dd');
d2.Format = 'dd MMM yyyy'
[year(d) month(d) day(d)]
day(d, 'name')MATLAB output:
d =
datetime
14-Mar-2025 15:09:26
d2 =
datetime
04 Jul 2025
ans =
2025 3 14
ans =
1×1 cell array
{'Friday'}Subtracting two datetimes gives a duration (an exact length of time), and functions such as hours, minutes and days both create durations and convert them back to numbers:
% MATLAB only
shift = datetime(2025,1,1,17,45,0) - datetime(2025,1,1,9,0,0)
hours(shift)
meeting = datetime(2025,1,1,9,0,0) + minutes(90)MATLAB output:
shift =
duration
08:45:00
ans =
8.7500
meeting =
datetime
01-Jan-2025 10:30:00Calendar units are different: a month or a year has no fixed length, so calmonths, calyears and caldays create a calendarDuration that follows the calendar. Adding one month to 31 January gives the last day of February:
% MATLAB only
datetime(2025, 1, 31) + calmonths(1:3)
dateshift(datetime(2025, 2, 10), 'end', 'month')MATLAB output:
ans =
1×3 datetime array
28-Feb-2025 31-Mar-2025 30-Apr-2025
ans =
datetime
28-Feb-2025datetimes also support comparisons (<, ==), sorting, isbetween, ranges like d1:caldays(7):d2, time zones ('TimeZone', 'Europe/Paris') and a Format property that only changes the display.
Serial date numbers
datenum turns a date into the number of days since the (fictional) date 0-Jan-0000. Whole numbers are midnight; the fractional part is the time of day:
t = datenum(2025, 3, 14, 15, 9, 26);
fprintf('serial number: %.6f\n', t);
fprintf('whole days: %d, fraction of day: %.4f\n', floor(t), t - floor(t));
fprintf('as hours since midnight: %.4f\n', (t - floor(t)) * 24);
disp(datestr(t))
noon = datenum(2025, 3, 14) + 0.5;
disp(datestr(noon))serial number: 739690.631551
whole days: 739690, fraction of day: 0.6316
as hours since midnight: 15.1572
14-Mar-2025 15:09:26
14-Mar-2025 12:00:00
Because a date is just a double, arithmetic is plain arithmetic: adding 1 adds a day, adding 1/24 adds an hour, and subtracting two dates gives a number of days. Out-of-range components roll over, so day 32 of January is 1 February:
startDay = datenum(2025, 7, 4);
xmas = datenum(2025, 12, 25);
fprintf('%d days from 4 July to Christmas\n', xmas - startDay);
disp(datestr(startDay + 30, 'yyyy-mm-dd'))
disp(datestr(datenum(2025, 1, 32), 'yyyy-mm-dd'))
disp(datestr(datenum(2025, 13, 1), 'yyyy-mm-dd'))
shift = datenum(2025,1,1,17,45,0) - datenum(2025,1,1,9,0,0);
fprintf('shift: %.2f hours = %d minutes\n', shift * 24, round(shift * 24 * 60));174 days from 4 July to Christmas
2025-08-03
2025-02-01
2026-01-01
shift: 8.75 hours = 525 minutes
Tip: Fractions of a day are rarely exact in binary floating point, so round when you convert to minutes or seconds, as the last line does with
round.
Formatting dates as text
datestr(t, format) builds text from a date number using format symbols. Watch out: these symbols differ from the ones datetime uses.
| Meaning | datestr symbol |
datetime Format symbol |
Example |
|---|---|---|---|
| Four-digit year | yyyy |
yyyy |
2025 |
| Month number | mm |
MM |
03 |
| Month name | mmm / mmmm |
MMM / MMMM |
Mar / March |
| Day of month | dd |
dd |
14 |
| Weekday name | ddd / dddd |
eee / eeee |
Fri / Friday |
| Hour (24 h) | HH |
HH |
15 |
| Minute | MM |
mm |
09 |
| Second | SS |
ss |
26 |
| AM/PM | PM |
a |
PM |
In datestr, lowercase mm is the month and uppercase MM the minute; datetime uses the international (Unicode) convention, which is the other way round. Mixing them up silently prints minutes where you expected months.
t = datenum(2025, 3, 14, 15, 9, 26);
disp(datestr(t, 'yyyy-mm-dd HH:MM:SS'))
disp(datestr(t, 'dddd, mmmm dd, yyyy'))
disp(datestr(t, 'HH:MM PM'))
disp(datestr(t, 'yyyy-MM-dd'))
disp(datestr(t, 31))2025-03-14 15:09:26
Friday, March 14, 2025
3:09 PM
2025-09-14
2025-03-14 15:09:26
The fourth line uses MM by mistake and prints the minute (09) in the middle. Numeric format codes such as 31 ('yyyy-mm-dd HH:MM:SS') are shorthand for common layouts.
Parsing text and splitting into parts
datenum(text, format) parses text, and datevec splits a date into a row [year month day hour minute second]:
d = datenum('2025-07-04 08:30', 'yyyy-mm-dd HH:MM');
v = datevec(d)
v2 = datevec('2025-11-30', 'yyyy-mm-dd');
fprintf('year %d, month %d, day %d\n', v2(1), v2(2), v2(3));
stamps = {'2025-01-05', '2024-12-24', '2025-03-01'};
dn = datenum(stamps, 'yyyy-mm-dd');
[~, order] = sort(dn);
disp(stamps(order))v =
2025 7 4 8 30 0
year 2025, month 11, day 30
{
[1,1] = 2024-12-24
[1,2] = 2025-01-05
[1,3] = 2025-03-01
}
Sorting date numbers sorts chronologically; sorting the original text only works when it's in year-month-day order.
Weekdays, month lengths and calendars
| Function | Returns |
|---|---|
weekday(t) |
Day number (1 = Sunday … 7 = Saturday) and a short name |
eomday(y, m) |
The number of days in that month (handles leap years) |
addtodate(t, n, unit) |
Date shifted by n years, months, days, hours, minutes… |
calendar(y, m) |
A 6x7 matrix of day numbers (zeros outside the month) |
now, clock, date |
The current date and time |
[n, name] = weekday(datenum(2025, 7, 4))
disp(eomday(2025, 1:12))
isLeap = @(y) eomday(y, 2) == 29;
disp(isLeap([1900 2000 2024 2025]))
months = addtodate(datenum(2025, 1, 31), [1 2 3], 'month');
disp(datestr(months, 'yyyy-mm-dd'))
disp(datestr(addtodate(datenum(2025,1,1,9,0,0), 90, 'minute'), 'HH:MM'))n = 6
name = Fri
31 28 31 30 31 30 31 31 30 31 30 31
0 1 1 0
2025-02-28
2025-03-31
2025-04-30
10:30
addtodate with months behaves like calmonths: 31 January plus one month is clamped to 28 February. The leap-year rule (every 4 years, except centuries, except every 400 years) comes for free from eomday.
calendar returns the month as a matrix whose columns are Sunday to Saturday, which is easy to print yourself:
c = calendar(2025, 2);
fprintf(' Su Mo Tu We Th Fr Sa\n');
for r = 1:size(c, 1)
if any(c(r, :))
row = sprintf('%4d', c(r, :));
fprintf('%s\n', strrep(row, ' 0', ' '));
end
end Su Mo Tu We Th Fr Sa
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
Ranges and grouping
A sequence of dates is just a numeric vector, so colon and vectorised functions do the work. This example builds every day of a two-week period and counts the weekend days:
span = datenum(2025, 6, 1):datenum(2025, 6, 14);
wd = weekday(span);
weekend = wd == 1 | wd == 7;
fprintf('%d days, %d on a weekend\n', numel(span), sum(weekend));
fprintf('weekend dates: %s\n', strjoin(cellstr(datestr(span(weekend), 'dd')), ' '));
mondays = span(wd == 2);
disp(datestr(mondays, 'ddd yyyy-mm-dd'))14 days, 4 on a weekend
weekend dates: 01 07 08 14
Mon 2025-06-02
Mon 2025-06-09
datestr of a vector returns a char matrix (one row per date); cellstr turns it into a cell array for strjoin.
Converting between the two worlds
If you use MATLAB's datetime but need to share code or data with older code, convert at the edges:
% MATLAB only
d = datetime(2025, 3, 14, 15, 9, 26);
dn = datenum(d) % datetime -> serial number
back = datetime(dn, 'ConvertFrom', 'datenum') % serial number -> datetime
posix = posixtime(d) % seconds since 1970-01-01 UTCMATLAB output:
dn =
7.3969e+05
back =
datetime
14-Mar-2025 15:09:26
posix =
1.7420e+09Excel serial dates count from 1900 instead of year 0; datetime(x, 'ConvertFrom', 'excel') handles them in MATLAB, and in Octave you can add the offset datenum(1899, 12, 30) yourself. For timing code rather than dating it, use tic and toc (see Performance & Preallocation).
Learn more: Tables (where datetime columns are common), pandas dates, Data Types & Classes and Reading & Writing Text Files.
Test yourself
What does datenum(2025,1,1) + 0.25 represent?
- 1 January 2025 at 06:00
- 1 January 2025 at 00:25
- 1 April 2025
- 25 January 2025
In a datestr format, which symbol prints the minutes?
MMmmminn
What is addtodate(datenum(2025,1,31), 1, 'month') as a date?
- 28 February 2025
- 3 March 2025
- 31 February 2025 (an error)
- 1 February 2025