Table of Contents
Introduction
MATLAB provides a dedicated datetime data type for representing calendar dates and times in a precise and readable way. In this chapter you learn how to create datetime arrays from scratch or from existing data, and how to control the way those dates and times are displayed using formats and locales.
Creating datetime Values
The basic way to create a single datetime value is to call the datetime function with no inputs. In that case MATLAB uses the current system date and time:
tNow = datetime
The output may look like 29-Dec-2025 15:42:10, depending on when you run it. The exact appearance is controlled by the Format property, which you will learn to change later.
You can also create a datetime by specifying its components with name-value arguments. For example, a specific calendar date and time can be created as:
t = datetime('Year', 2025, 'Month', 12, 'Day', 29, ...
'Hour', 9, 'Minute', 30, 'Second', 0);
Here Year, Month, Day, Hour, Minute, and Second are property names, and the numbers you pass are their values. If you omit time components, MATLAB fills in zeros, so you can write:
tDateOnly = datetime('Year', 2025, 'Month', 12, 'Day', 1);which represents midnight at the start of 1 December 2025.
Creating datetime Arrays
You rarely work with a single timestamp. MATLAB can store many datetime values in one array, just like numeric vectors and matrices.
If you provide vector inputs to the component arguments, MATLAB creates an array of the corresponding size. For instance:
years = [2023 2024 2025];
months = [ 1 6 12 ];
days = [ 10 15 20 ];
tArr = datetime('Year', years, 'Month', months, 'Day', days);
The result tArr is a 1-by-3 datetime array. Indexing and shape rules are the same as for numeric arrays. You can create column vectors in the same way:
years = (2020:2024)'; % column vector
months = ones(5,1); % all January
days = 1:5; % row vector
days = days'; % make it a column
tCol = datetime('Year', years, 'Month', months, 'Day', days);All component vectors must be compatible in size, so MATLAB can combine them element by element.
Creating Regular Sequences with datetime
A very common use is to create regularly spaced sequences, such as every day, every month, or every minute. For this you can use the colon operator with datetime, similar to numeric ranges.
The general pattern is:
tStart : step : tEnd
where tStart and tEnd are datetime values, and step is a duration or calendarDuration value.
For fixed-length steps such as hours, minutes, or seconds, you use duration:
tStart = datetime(2025,1,1,0,0,0);
tEnd = datetime(2025,1,1,6,0,0);
step = hours(1); % a duration of 1 hour
tHourly = tStart:step:tEnd;
Here tHourly contains 7 hourly timestamps from midnight to 6 a.m.
For calendar based steps such as months or years that vary in actual length, you use calmonths, calyears, or caldays which create calendarDuration values:
tStart = datetime(2025,1,1);
tEnd = datetime(2025,12,1);
step = calmonths(1); % a calendarDuration of 1 month
tMonthly = tStart:step:tEnd;
The array tMonthly contains the first day of each month from January to December 2025, regardless of how many days are in each month.
If you only specify two datetime values with the colon operator, MATLAB uses a default step of one calendar day:
tDaily = datetime(2025,1,1) : datetime(2025,1,10);This creates daily dates from January 1 to January 10, 2025.
Constructing datetime from Text
Many real data sets store dates and times as text, often in files or tables. You can convert such text to datetime using the datetime function with a Format description that matches how the text is written.
Assume you have a character vector:
txt = '2025-12-29 09:30:00';
t = datetime(txt, 'InputFormat', 'yyyy-MM-dd HH:mm:ss');
Here InputFormat tells MATLAB how to interpret each part of the text. The pattern yyyy-MM-dd HH:mm:ss speaks about four-digit year, two-digit month, two-digit day, space, hours in 24 hour format, minutes, and seconds.
You can handle text that contains only a date without a time:
dStr = "03/15/2025"; % string scalar
d = datetime(dStr, 'InputFormat', 'MM/dd/yyyy');
Note that you supply the InputFormat that matches the text exactly. If the text contains named months, such as "29-Dec-2025", the input format might be:
dStr = "29-Dec-2025";
d = datetime(dStr, 'InputFormat', 'dd-MMM-yyyy');
Here MMM stands for the short month name.
You can convert many strings at once, as long as the array of text is the same size as the output datetime array:
timesStr = ["2025-01-01" "2025-01-02" "2025-01-03"];
tArr = datetime(timesStr, 'InputFormat', 'yyyy-MM-dd');
Now tArr is a row vector of three datetime values.
Automatic Format Detection
If you omit InputFormat when converting from text, MATLAB attempts to detect the format automatically. For example:
d = datetime("2025-12-29");
This usually works for common formats, especially ISO style dates like yyyy-MM-dd. However, automatic detection can fail or interpret dates differently than you intend when formats are ambiguous. For complete control and reproducibility, it is safer to always specify InputFormat when you know the pattern.
Basic Formatting Concepts
Each datetime value has a Format property that controls how it is displayed in the Command Window or when printed. The underlying stored value does not change when you change the format, only the display changes.
You can inspect the format of a datetime array using dot notation:
t = datetime(2025,12,29,9,30,0);
t.Format
By default, MATLAB assigns a reasonable format when you create the datetime, such as 'dd-MMM-yyyy HH:mm:ss' or a similar pattern.
You can change it directly:
t.Format = 'yyyy/MM/dd HH:mm';
t
Now when you display t, you will see 2025/12/29 09:30.
You can set the format on an entire array at once:
tArr = datetime(2025,1,1) + days(0:4);
tArr.Format = 'dd/MM/yyyy';
tArr
All elements of tArr share the same Format setting.
Common Format Patterns
Formatting datetime values uses pattern letters that represent components of the date and time. Some commonly used patterns are:
yyyy represents a four digit year, for instance 2025.
yy represents a two digit year, such as 25 for 2025.
MM represents a two digit month number, from 01 to 12.
MMM represents a short month name, such as Jan or Dec.
MMMM represents the full month name, such as January or December.
dd represents a two digit day of the month, such as 01 through 31.
EEE or eee often represent short day of week names, such as Mon or Tue, depending on the locale.
HH represents the hour of the day from 00 to 23 in 24 hour time.
hh represents the hour in 12 hour time, with an associated a or aa for AM or PM.
mm represents minutes, from 00 to 59.
ss represents whole seconds, and SSS or broader patterns can represent fractional seconds if present.
You can combine these patterns with punctuation as needed. For example:
t = datetime(2025,12,29,9,30,5);
t.Format = 'dd-MMM-yyyy';
t
t.Format = 'yyyyMMdd_HHmmss';
t
t.Format = 'EEEE, MMMM dd, yyyy HH:mm';
t
Each time you change t.Format, the display of t changes. Components that are not included in the format string do not disappear, they are still present in the underlying value and can be accessed later.
Formatting for Date Only or Time Only
Sometimes you only care about the date or only the time of day. You can select formats that show only what you need.
For date only:
t = datetime(2025,12,29,9,30,0);
t.Format = 'yyyy-MM-dd';For time only:
t.Format = 'HH:mm:ss';In both cases the full date and time information is still stored internally. The format only affects how it appears.
Locale and Language of Month and Day Names
If your format string uses text components such as month or day names, their language and spelling depend on the locale MATLAB uses for datetime formatting.
You can set the default locale of the environment before creating datetimes, typically using functions or preferences in MATLAB that control language and region. For named months and days, the same Format pattern can produce different text according to the current locale.
For example, if your locale is set to English you may see:
t = datetime(2025,12,29);
t.Format = 'dd-MMM-yyyy EEEE';
t
and the output might be 29-Dec-2025 Monday. With another locale, month and day names will appear in a different language.
Although you usually do not need to manage the locale explicitly when beginning, it is important to know that month names are not fixed in English if the environment uses another language.
Controlling Default Display with datetime Preferences
When you create new datetime values without specifying a format explicitly, MATLAB chooses a default format. For interactive work you might prefer a different default. You can control this behavior using MATLAB preferences.
In the MATLAB Desktop you can open the Preferences dialog, navigate to formats for dates and times, and select a default output format. Once set, new datetime arrays that you create will use that format unless you override it by setting their Format property.
Programmatically, you typically prefer to set Format explicitly in your code for clarity and robustness, instead of relying on a global preference. This is especially important if you share code with others or run it on different systems.
Viewing and Editing the Format of Existing datetime Arrays
If you already have a datetime array, for instance from imported data, you can change its display format at any time. Suppose tData is a column of datetimes loaded from a file:
tData = datetime(["2025-01-01 00:00:00";
"2025-01-01 06:00:00";
"2025-01-01 12:00:00"], ...
'InputFormat', 'yyyy-MM-dd HH:mm:ss');Initially the format might be the default. To change it:
tData.Format = 'dd/MM/yyyy HH:mm';
Now when you display tData the dates use the new format. If you store tData in a table, the display in the table will also use that format.
You can store a datetime array in variables, tables, or timetables, and the Format setting travels with the data. This makes it easier to control how dates and times appear wherever they are shown.
Formatting for Interchange and File Names
Sometimes you create text versions of dates to use in filenames or for interoperability with other systems. You control this by combining datetime with string or char conversion and a chosen format.
Set the format you want, then convert:
t = datetime(2025,12,29,9,30,0);
t.Format = 'yyyyMMdd_HHmmss';
fileStamp = char(t); % or string(t)
filename = ['log_' fileStamp '.txt'];
Here the format "yyyyMMdd_HHmmss" creates compact text that is easy to sort lexicographically and safe to use in file names.
Note that converting to text is different from changing the display format. When you convert to text, you get a new text array. The datetime value remains a datetime and still uses whatever format you have set for display.
Handling Time Zones in Formatting
datetime values can optionally include a time zone. Formatting can display the time zone abbreviation or offset if you include it in the pattern with z or related symbols. For example, if you create a datetime with a time zone:
t = datetime(2025,12,29,9,30,0, 'TimeZone', 'Europe/London');
t.Format = 'yyyy-MM-dd HH:mm z';
t
The display might include GMT or BST depending on daylight saving time rules at that date. If you do not include a zone pattern in the format, the time zone may not be visible even though the information is present.
Creating and manipulating time zones is a broader topic that is treated separately. At this stage you only need to know that some format patterns influence whether the zone appears in the textual representation.
Summary of Key Ideas
Creating and formatting datetime arrays is mostly about two skills. First, you learn to create datetime values from components, from regular sequences, or by converting text. Second, you learn to control the display by setting the Format property with pattern letters that represent date and time components.
Once you understand these ideas, you can prepare your time related data for analysis, plotting, and storage in a way that is both precise and clear to read.
Important points to remember:
- Use
datetimeto create date and time values, either from components, from text withInputFormat, or as regular sequences with duration or calendarDuration steps. - The
Formatproperty controls only the display of adatetime, not its stored value. Changing the format does not change the underlying date or time. - Always specify
InputFormatwhen converting from text if the pattern is not obvious or could be ambiguous. This avoids misinterpreted dates. - Use pattern letters like
yyyy,MM,dd,HH,mm, andssto design custom formats that fit your needs for tables, plots, and filenames. - All elements of a
datetimearray share the sameFormat. When you set the format on the array, you control how every element is displayed.