Main Content

Convert Between Datetime Arrays, Numbers, and Text

Overview

datetime is the best data type for representing points in time. datetime values have flexible display formats and up to nanosecond precision, and can account for time zones, daylight saving time, and leap seconds. However, if you work with code authored in MATLAB® R2014a or earlier, or if you share code with others who use such a version, you might need to work with dates and time stored in one of these three formats:

  • Date String — A character vector.

    Example:  Thursday, August 23, 2012  9:45:44.946 AM
  • Date Vector — A 1-by-6 numeric vector containing the year, month, day, hour, minute, and second.

    Example:  [2012   8    23    9    45    44.946]
    
  • Serial Date Number — A single number equal to the number of days since January 0, 0000 in the proleptic ISO calendar (specifying use of the Gregorian calendar). Serial date numbers are useful as inputs to some MATLAB functions that do not accept the datetime or duration data types.

    Example:  7.3510e+005

Date strings, vectors, and numbers can be stored as arrays of values. Store multiple date strings in a cell array of character vectors, multiple date vectors in an m-by-6 matrix, and multiple serial date numbers in a matrix.

You can convert any of these formats to a datetime array using the datetime function. If your existing MATLAB code expects a serial date number or date vector, use the datenum or datevec functions, respectively, to convert a datetime array to the expected data format. To convert a datetime array to character vectors, use the char or cellstr functions.

Starting in R2016b, you also can convert a datetime array to a string array with the string function.

Convert Between Datetime and Character Vectors

A date string can be a character vector composed of fields related to a specific date and/or time. There are several ways to represent dates and times in text format. For example, all of the following are character vectors representing August 23, 2010 at 04:35:42 PM:

'23-Aug-2010 04:35:06 PM'
'Wednesday, August 23'
'08/23/10 16:35'
'Aug 23 16:35:42.946'

A date string includes characters that separate the fields, such as the hyphen, space, and colon used here:

d = '23-Aug-2010 16:35:42'	

Convert one or more date strings to a datetime array using the datetime function. For best performance, specify the format of the input date strings as an input to datetime.

Note

The specifiers that datetime uses to describe date and time formats differ from the specifiers that the datestr, datevec, and datenum functions accept.

For a complete list of date and time format specifiers, see the Format property of the datetime data type.

t = datetime(d,'InputFormat','dd-MMM-yyyy HH:mm:ss')
t = 

  datetime

   23-Aug-2010 16:35:42

Although the date string, d, and the datetime scalar, t, look similar, they are not equal. View the size and data type of each variable.

whos d t
  Name      Size            Bytes  Class       Attributes

  d         1x20               40  char                  
  t         1x1                17  datetime              

Convert a datetime array to a character vector using char or cellstr. For example, convert the current date and time to a timestamp to append to a file name.

t = datetime('now','Format','yyyy-MM-dd''T''HHmmss')
t = 

  datetime

   2017-01-03T151105
S = char(t);
filename = ['myTest_',S]
filename =

    'myTest_2017-01-03T151105'

Convert Between Datetime and String Arrays

Starting in R2016b, you can use the string function to create a string array. If a string array contains date strings, then you can convert the string array to a datetime array with the datetime function. Similarly, you can convert a datetime array to a string array with the string function.

Convert a string array. MATLAB displays strings in double quotes. For best performance, specify the format of the input date strings as an input to datetime.

str = string({'24-Oct-2016 11:58:17';
              '19-Nov-2016 09:36:29';
              '12-Dec-2016 10:09:06'})
str = 

  3×1 string array

    "24-Oct-2016 11:58:17"
    "19-Nov-2016 09:36:29"
    "12-Dec-2016 10:09:06"
t = datetime(str,'InputFormat','dd-MMM-yyyy HH:mm:ss')
t = 

  3×1 datetime array

   24-Oct-2016 11:58:17
   19-Nov-2016 09:36:29
   12-Dec-2016 10:09:06

Convert a datetime value to a string.

t = datetime('25-Dec-2016 06:12:34');
str = string(t)
str = 

     "25-Dec-2016 06:12:34"

Convert Between Datetime and Date Vectors

A date vector is a 1-by-6 vector of double-precision numbers. Elements of a date vector are integer-valued, except for the seconds element, which can be fractional. Time values are expressed in 24-hour notation. There is no AM or PM setting.

A date vector is arranged in the following order:

year month day hour minute second

The following date vector represents 10:45:07 AM on October 24, 2012:

[2012  10  24  10  45  07]

Convert one or more date vectors to a datetime array using the datetime function:

t = datetime([2012  10  24  10  45  07])
t = 

  datetime

   24-Oct-2012 10:45:07

Instead of using datevec to extract components of datetime values, use functions such as year, month, and day instead:

y = year(t)
y =

        2012

Alternatively, access the corresponding property, such as t.Year for year values:

y = t.Year
y =

        2012

Convert Serial Date Numbers to Datetime

A serial date number represents a calendar date as the number of days that has passed since a fixed base date. In MATLAB, serial date number 1 is January 1, 0000.

Serial time can represent fractions of days beginning at midnight; for example, 6 p.m. equals 0.75 serial days. So the character vector '31-Oct-2003, 6:00 PM' in MATLAB is date number 731885.75.

Convert one or more serial date numbers to a datetime array using the datetime function. Specify the type of date number that is being converted:

t = datetime(731885.75,'ConvertFrom','datenum')
t = 

  datetime

   31-Oct-2003 18:00:00

Convert Datetime Arrays to Numeric Values

Some MATLAB functions accept numeric data types but not datetime values as inputs. To apply these functions to your date and time data, convert datetime values to meaningful numeric values. Then, call the function. For example, the log function accepts double inputs, but not datetime inputs. Suppose that you have a datetime array of dates spanning the course of a research study or experiment.

t = datetime(2014,6,18) + calmonths(1:4)
t = 

  1×4 datetime array

   18-Jul-2014   18-Aug-2014   18-Sep-2014   18-Oct-2014

Subtract the origin value. For example, the origin value might be the starting day of an experiment.

dt = t - datetime(2014,7,1)
dt = 

  1×4 duration array

    408:00:00   1152:00:00   1896:00:00   2616:00:00

dt is a duration array. Convert dt to a double array of values in units of years, days, hours, minutes, or seconds using the years, days, hours, minutes, or seconds function, respectively.

x = hours(dt)
x =

         408        1152        1896        2616

Pass the double array as the input to the log function.

y = log(x)
y =

    6.0113    7.0493    7.5475    7.8694

See Also

| | | | | |

Related Topics