Converting Date Vector Returns Unexpected Output
Note The best practice is to use datetime values to represent points in time rather than date
vectors. Unlike date vectors, datetime values display in a human-readable format, often avoiding
the need for conversion to text. If you need to convert a date vector to text, the best practice is to
first convert it to a datetime value, and then to convert the datetime value to text by using the
string or char functions. While you can convert date vectors to text directly by using the datestr
function, you might get unexpected results, as described in this section.
Because a date vector is a 1-by-6 row vector of numbers, the datestr function might interpret input
date vectors as vectors of serial date numbers and return unexpected output. Or it might interpret
vectors of serial date numbers as date vectors. This ambiguity exists because datestr has a
heuristic rule for interpreting a 1-by-6 row vector as either a date vector or a vector of six serial date
numbers. The same ambiguity applies to inputs that are m-by-6 numeric matrices, where each row
can be interpreted either as a date vector or as six serial date numbers.
For example, consider a date vector that includes the year 3000. This year is outside the range of
years that datestr interprets as elements of date vectors. Therefore, the input is interpreted as a 1by-6 vector of serial date numbers.
d = datestr([3000 11 05 10 32 56])
d =
6×11 char array
'18-Mar-0008'
'11-Jan-0000'
'05-Jan-0000'
'10-Jan-0000'
'01-Feb-0000'
'25-Feb-0000'
Here datestr interprets 3000 as a serial date number, and converts it to the text '18-Mar-0008'
(the date that is 3000 days after 0-Jan-0000). Also, datestr converts the next five elements as
though they also were serial date numbers.
There are two methods for converting such a date vector to text.
• The recommended method is to convert the date vector to a datetime value. Then convert it
using the char, cellstr, or string function. The datetime function always treats 1-by-6
numeric vectors as date vectors.
dt = datetime([3000 11 05 10 32 56]);
ds = string(dt)
dt =
"05-Nov-3000 10:32:56"
• As an alternative, convert it to a serial date number using the datenum function. Then, convert
the date number to a character vector using datestr.
dn = datenum([3000 11 05 10 32 56]);
ds = datestr(dn)
7 Dates and Time
7-48
Précédent

- 302/1450

Suivant