Skip to Main Content Skip to Search
Product Documentation

Dates and Times

Representing Dates and Times in MATLAB

The MATLAB software represents date and time information in any of three formats:

You have the choice of using any of these formats. If you work with more than one date and time format, MATLAB provides functions to help you easily convert from one format to another.

Dates and Dates with Time

You can work either with dates alone, or with dates and times combined. This table shows both options in the default date number, vector, and string formats.

 DateDate and Time
Date NumberDays since Jan 1, 0000
n=734455  (n is whole)
Days since Jan 1, 0000
n = 734455.36  (n is real)
Date Vector[year month day 0 0 0]
[2010 11 13 0 0 0]
[year month day hour min sec]
[2010 11 13 8 35 24]
Date Stringday-month-year
'13-Nov-2010'
day-month-year hour:min:sec
'13-Nov-2010 08:35:24'

These formats also support elapsed time. See Using Serial Date Numbers For Elapsed Time for more information.

Date and Time Functions

This table shows what information is available in MATLAB with respect to dates and times and which function provides this information. The sections that follow the table provide more information on how to use the different date and time formats.

Date and Time InformationOutput FormatFunction to Use
Current date and timeDate numbernow
Date vectorclock
Date stringdatestr(now)
Current dateDate numberdatenum(date)
Date vectordatevec(date)
Date stringdate
Day of week for given dateFull day name, abbreviated name, or day number in week (1-7)weekday
Last day of given month(s)Vector of one or more dayseomday
Date with modified fieldDate numberaddtodate
Calendar for given month6-by-7 matrix of dayscalendar

For examples showing how to use these functions, see the function reference documentation.

Working with Date Strings

There are a number of ways to represent dates and times in character string format. For example, all of the following are date strings for 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'

Creating Date Strings In MATLAB

A date string is a character string composed of fields related to a specific date and/or time. In its default form, a date string has six fields containing values for a specific day, month, year, hour, minute, and second, in that order:

'23-Aug-2010 16:35:10'

A default date string that contains just a date consists of three fields: day, month, and year. The date function returns this type of date string:

date
ans =
    23-Aug-2010

To create a date string, you simply enter it as a MATLAB character string. Include any characters you might need to separate the fields, such as the hyphen, space, and colon used here:

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

Minimum Requirements for Date Strings.  A date string must contain at least a month and day field, or an hour and minute field. When entering month and day fields, MATLAB expects the month to precede the day. (There are ways to reverse this order, but that is more advanced usage and is documented under How to Use the Field Specifier.) The following date string is August 12, not December 8:

d = '08/12'

When entering the hour and minute fields, put the hour first and separate the two fields with a colon. The following date strings are 10:35 in the morning and 3:20 in the afternoon in both 24-hour and 12-hour notation:

t = '10:35'     t = '10:35 AM'
t = '15:20'     t = '3:20 PM'

If the date includes the year, then the year value must immediately precede or immediately follow the month and day. The following are both valid date strings that represent the same day, August 12 in the year 2010:

d = '08/12/2010'
d = '2010/08/12'

When unspecified, the year defaults to the current year, month and day default to January 1, hour and minute default to 00:00, and second and millisecond default to 00.000.

Specifying the Fields of a Date String

The MATLAB software provides the datevec, datenum, and datestr functions for converting from one date format to another. When you pass a date string to one of these functions, MATLAB does not necessarily know which fields have been included in the string, or the order in which they are positioned. Also, if you expect a date string to be returned by one of the conversion functions, you might need to indicate how that string is to be composed. For these reasons, unless you are passing a date string that uses the default field format, MathWorks recommends that you pass an additional argument called a field specifier in the call.

How to Use the Field Specifier.  The reference page syntax for date conversion functions identifies the field specifier arguments as FieldSpecIn and FieldSpecOut. The datevec and datenum functions use the FieldSpecIn argument to indicate how MATLAB is to interpret the input date string:

DateVector = datevec(DateString, FieldSpecIn)

The datestr function uses the FieldSpecOut argument to indicate how MATLAB is to display the output date string:

DateString = datestr(DateVector, FieldSpecOut)

If you need to use a field specifier for both input and output strings, nest a call to datenum inside a call to datestr or datevec. This example changes date string 'August 11' to '11 August'. Because neither string is in the default format, you need a field specifier for both the input and output date strings:

datestr(datenum('August 11', 'mmmm dd'), 'dd mmmm')
ans =
    11 August

Character-Based Field Identifiers.  There are two types of identifiers with which you can indicate the layout of fields in a date string. The more general of the two employs character-based symbols, such as those shown in this table, to designate the fields of a date string. (See Symbolic Identifiers for Individual Fields for the full table).

FieldExampleIdentifier
Year (in 4 digits)2010yyyy
Month (in 3 characters)Augmmm
Day Number23dd
Hour16HH
Minute35MM
Second42 SS

The goal of the following example is to convert the date vector [2010 08 23 16 35 00] to a date string that has the nondefault format:

2010-08-23 16:35:42

Look up each of the six date fields in the table and use the symbols you find to compose a field specifier string that tells MATLAB how you want the date string output to look:

InputVector = [2010 08 23 16 35 42];

datestr(InputVector, 'yyyy-mm-dd HH:MM:SS')
ans =
    2010-08-23 16:35:42

Numeric Field Identifiers.  There is an additional method for indicating the type of format you want applied to a date string. The MATLAB software associates 31 commonly used field sequences with a numeric identifier for each. Using these predefined formats can simplify the creation of your date strings. The table below shows several of these identifiers and the type of date string associated with them. (See Numeric Identifiers for Predefined Formats for the full table).

Date String FormatsExample of OutputIdentifier to Use
'dd-mmm-yyyy'01-Mar-20001
'HH:MM:SS PM'3:45:17 PM14
'mm/dd/yyyy'03/01/200023
'dd/mm/yyyy'01/03/200024
'yyyy-mm-dd HH:MM:SS'2000-03-01 15:45:1731

Repeat the example from the previous section, this time using a numeric field specifier:

InputVector = [2010 08 23 16 35 42];

datestr(InputVector, 31)
ans =
    2010-08-23 16:35:42

Compare the commands used to achieve the same result. The advantage of the character-based field specifiers is that they are more versatile and easier to remember. The advantage of the numeric field specifiers is that frequently used commands are easier to enter:

datestr(InputVector, 'yyyy-mm-dd HH:MM:SS')    % Character
datestr(InputVector, 31)                       % Numeric

Adding Field Separation Characters.  It is customary to separate certain fields of a date string with some form of punctuation, such as commas or space characters. Insert these characters into a date string by including them in the field specifier string. You cannot use any characters that could conflict with those symbolic characters reserved for use in the FieldSpecIn or fieldSpecOut strings (for example, y, m, H, M, and so on).

Add separation characters to make a date string easier to read:

datestr(now, 'dddd, mmmm dd, yyyy HH:MM')
ans =
    Wednesday, August 23, 2010 16:35

Creating Multiple Date Strings

Calling datestr with more than one date string input returns a character array of converted date strings. Pass the multiple date strings in a cell array. All input date strings must use the same format. For example, the following command passes three dates that all use the mm/dd/yyyy format:

datestr(datenum({'09/16/2007';'05/14/1996';'11/29/2010'}, ...
    'mm/dd/yyyy'))
ans =
    16-Sep-2007
    14-May-1996
    29-Nov-2010

Time Display in Date Strings

In MATLAB, you can represent time in a date string using either a 12-hour or 24-hour system in MATLAB. The following table shows how to create a 12-hour time string in the first column, and how to convert that time to its 24-hour equivalent.

12-hour timeCommand to convert to 24-hour formatEquivalent 24-hour time
05:32 AMdatestr('05:32 AM', 'HH:MM')5:32
05:32 PMdatestr('05:32 PM', 'HH:MM')17:32

The next table shows how to create a 24-hour time string in the first column, and how to convert that time to its 12-hour equivalent.

24-hour timeCommand to convert to 12-hour formatEquivalent 12-hour time
05:32datestr('05:32', 'HH:MM PM')5:32 AM
17:32datestr('17:32', 'HH:MM PM')5:32 PM

A few other things to remember when specifying time in MATLAB are:

Date String Tables

Symbolic Identifiers for Individual Fields

The following table shows:

FieldString FormatExample of OutputField Identifier
Quarter yearLetter Q and 1 digitQ4'QQ'
Year4 digits2007'yyyy'
2 digits07'yy'
MonthFull nameDecember'mmmm'
First 3 lettersDec'mmm'
2 digits12'mm'
First letterD'm'
DayFull nameTuesday'dddd'
First 3 lettersTue'ddd'
2 digits20'dd'
First letterT'd'
Hour2 digits16'HH'
Minute2 digits02'MM'
Second2 digits54'SS'
MillisecondDecimal point and 3 digits.057'FFF'
12-hour periodAM or PMPM'AM' or 'PM'

Notes Concerning Usage.  Here are a few points to remember when using the symbolic identifiers:

MATLAB interprets the field specifiers in this table according to your computer's language setting and the current MATLAB language setting.

In a field specifier string, you cannot specify any field more than once. For example, you cannot use 'yy-mmm-dd-m' because it has two month identifiers. The one exception to this is that you can combine one instance of dd with one instance of any of the other day identifiers:

ds = datestr(now, 'dddd  mmm dd yyyy')
ds =
    Wednesday  Jun 30 2010

You only can use QQ (quarter of the year) alone or with a year specifier.

Numeric Identifiers for Predefined Formats

The following table shows numeric identifiers you can use to include certain field and format combinations in a date string.

Date String FormatsExample of OutputIdentifier to Use
'dd-mmm-yyyy HH:MM:SS'01-Mar-2000 15:45:170
'dd-mmm-yyyy'01-Mar-20001
'mm/dd/yy'03/01/002
'mmm'Mar3
'm'M4
'mm'035
'mm/dd'03/016
'dd'017
'ddd'Wed8
'd'W9
'yyyy'200010
'yy'0011
'mmmyy'Mar0012
'HH:MM:SS'15:45:1713
'HH:MM:SS PM'3:45:17 PM14
'HH:MM'15:4515
'HH:MM PM'3:45 PM16
'QQ-YY'Q1-0117
'QQ'Q118
'dd/mm'01/0319
'dd/mm/yy'01/03/0020
'mmm.dd,yyyy HH:MM:SS'Mar.01,2000 15:45:1721
'mmm.dd,yyyy'Mar.01,200022
'mm/dd/yyyy'03/01/200023
'dd/mm/yyyy'01/03/200024
'yy/mm/dd'00/03/0125
'yyyy/mm/dd'2000/03/0126
'QQ-YYYY'Q1-200127
'mmmyyyy'Mar200028
'yyyy-mm-dd' (ISO 8601)2000-03-0129
'yyyymmddTHHMMSS' (ISO 8601)20000301T15451730
'yyyy-mm-dd HH:MM:SS'2000-03-01 15:45:1731

Working with Date Vectors

Date vectors are an internal format for some MATLAB functions. You do not typically use date vectors in calculations, although you can use them to perform some simple computations such as the one shown in the example in this section.

A date vector is a 1-by-6 matrix of double-precision numbers arranged in the following order.

year month day hour minute second

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

[2009  10  24  10  45  07]

The fields of a date vector must follow these guidelines:

Creating a Date Vector

As with any vector, you can create a date vector just as shown here. Be sure to put the fields in the correct order:

dv = [2010 8 23 16 35 42];

You can also create a date vector by converting a date string or serial date number. The datevec function converts from a date string or serial date number to a date vector.

Converting from Date String to Date Vector

The first argument to datevec can be a date string. If this string is in the default format for a date string, then you need only the one input argument:

dv = datevec('23-Aug 2010 16:35')
dv =
     2010      8     23     16     35      0

If the date string is in a nondefault date string format such as the one shown below, it is recommended that you also pass a field specifier argument. This argument tells MATLAB how the input string has been formatted:

dv = datevec('August 23, 2010 16:35', 'mmmm dd, yyyy HH:MM')
dv =
     2010      8     23     16     35      0

The tables Symbolic Identifiers for Individual Fields and Numeric Identifiers for Predefined Formats list all of the format specifiers for date strings. When converting from a date string to a date vector, you can use any string from these tables.

Converting from Serial Date Number to Date Vector

To convert from a serial date number to a date vector, pass only the date number argument:

dv = datevec(7.343736909722223e+005)
dv =
     2010      8     23     16     35      0

This argument can be the output of a function that yields a serial date number such as the now function:

dv = datevec(now)
dv =
  1.0e+003 *
    2.0100    0.0060    0.0290    0.0100    0.0350    0.0460

Creating Multiple Date Vectors

Calling datevec with more than one date string input returns a character array of converted date strings. Pass the multiple date strings in a cell array. All input date strings must use the same format. For example, the following command passes three dates that all use the mm/dd/yyyy format:

datevec({'09/16/2007';'05/14/1996';'11/29/2010'})
ans =
    2007       9      16       0       0       0
    1996       5      14       0       0       0
    2010      11      29       0       0       0

Milliseconds in Serial Date Numbers

Date vectors have no separate field in which to specify milliseconds. However, the seconds field has a fractional part and accurately keeps the milliseconds field. This example converts a date string with 647 milliseconds into a vector, and then converts it back into a string. Note that MATLAB fully restores the milliseconds count:

datenum([2010      8     23     16     35      0])
ans =
  7.3437e+005
dvec = datevec('11:21:02.647', 'HH:MM:SS.FFF')
dvec =
  1.0e+003 *
    2.0100    0.0010    0.0010    0.0110    0.0210    0.0026

datestr(dvec, 'HH:MM:SS.FFF')
ans =
   11:21:02.647

Examples of Using Date Vectors

Distribute the three time values in this vector to separate output variables:

[~, ~, ~, hour, min, sec] = datevec(now)
hour =
    11
min =
    47
sec =
   19.4660

Construction of the Eiffel Tower was begun on January 26 in 1887 and completed on March 31, 1889. This example finds the difference between the year, month, and day elements of the starting and ending date vectors to compute the time the tower was under construction:

startDate  = [1887  1  26  0  0  0];       % January 26, 1887
finishDate = [1889  3  31  0  0  0];       % March 31, 1889

t = finishDate - startDate
t =
     2     2     5     0     0     0

[fprintf('\nThe Eiffel Tower took %d years, ', t(1)) ...
 fprintf('%d months, and %d days to construct.\n', t(1), t(2))];

The Eiffel Tower took 2 years, 2 months, and 2 days to construct.

Working with Serial Date Numbers

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. MATLAB also uses serial time to represent fractions of days beginning at midnight; for example, 6 p.m. equals 0.75 serial days. So the string '31-Oct-2003, 6:00 PM' in MATLAB is date number 731885.75.

MATLAB works internally with serial date numbers. If you are using functions that handle large numbers of dates or doing extensive calculations with dates, you get better performance if you use date numbers.

You can create a serial date number from a date string or date vector using the following commands:

Converting from Date String to Serial Date Number

The first argument to datenum can be a date string. If this string is in the default format for a date string, then you need only the one input argument:

dv = datenum('23-Aug 2010 16:35')
dn =
    7.3437e+005

If the date string is in a nondefault date string format such as the one shown below, it is recommended that you also pass a field specifier argument. The field specifier tells MATLAB how the input string has been formatted:

dn = datenum('August 23, 2010 16:35', 'mmmm dd, yyyy HH:MM')
dn =
  7.3437e+005

The tables Symbolic Identifiers for Individual Fields and Numeric Identifiers for Predefined Formats list all of the format specifiers for date strings. When converting from a date string to a serial date number, you can use any string from these tables.

Certain formats may not contain enough information to compute a date number. In these cases, hours, minutes, seconds, and milliseconds default to 0, the month defaults to January, the day to 1, and the year to the current year.

Converting from Date Vector to Serial Date Number

To convert from a date vector to a serial date number, pass just the date vector argument:

datenum([2010 8 23 16 35 42])
ans =
    7.3437e+005

This argument can be the output of a function that yields a date vector such as the clock function:

dv = clock
dv =
  1.0e+003 *
    2.0100    0.0060    0.0290    0.0110    0.0130    0.0057

datenum(dv)
ans =
  7.3432e+005

Creating Multiple Serial Date Numbers

Calling datenum with more than one date string input returns a character array of converted date strings. Pass the multiple date strings in a cell array. All input date strings must use the same format. For example, the following command passes three dates that all use the mm/dd/yyyy format:

datenum({'09/16/2007';'05/14/1996';'11/29/2010'})
ans =
    733301
    729159
    734471

Using Serial Date Numbers For Elapsed Time

To find the time elapsed between two events, subtract the starting time from the ending time using serial date number format.

This example computes the time elapsed between 8:15 AM and 3:45 PM on different days. Create two strings containing the starting and ending time:

s1 = '20-Apr 8:15';   s2 = '23-Apr 15:45';

Convert date strings to serial date numbers:

n1 = datenum(s1, 'dd-mmm HH:MM');
n2 = datenum(s2, 'dd-mmm HH:MM');

Subtract the starting time from the ending time:

n = n2 - n1
n =
    3.3125

Convert the answer to a string:

days = floor(n);
hrs = datestr(n, 'HH');
mins = datestr(n, 'MM');

fprintf('\n   %d days, %s hours, %s minutes\n', ...
   days, hrs, mins);

   3 days, 07 hours, 30 minutes

Examples of Using Serial Date Numbers

Add 50 days to the serial date number returned by the now function:

fprintf('\n   In 50 days it will be %s.\n', ...
datestr(now+50, 'dddd, mmmm dd'))

   In 50 days it will be Saturday, July 10.

Using the addtodate function, add 20 days to the date 20-Jan-2002. This date is first converted to a date number by a nested call to datenum:

addtodate(datenum('20.01.2002','dd.mm.yyyy'),20,'day')
R =
      731256

Other Considerations

Carrying to the Next Field

Where reasonable, MATLAB automatically carries values outside the normal range of each unit to the next field. For example, specifying a date vector with a month value of 14 affects the output by setting the month to February and incrementing the year value by 1. The carrying forward of values applies only to date vectors and to time and day values in date strings, carries the 10 extra months from the input date string 22/03/2009 into October of the following year:

datestr([2009 22 03 00 00 00])
ans =
    03-Oct-2010

All units can wrap and have negative values. Note that specifying a negative day value, D, sets the output to the last day of the previous month minus |D|. This example takes the input month (07, or July), finds the last day of the previous month (June 30), and subtracts the number of days in the field specifier (5 days) from that date to yield a return date of June 25, 2010:

datestr([2010 07 -05 00 00 00])
ans =
    25-Jun-2010

Specifying a Pivot Year

Use the pivot year to interpret date strings that specify the year using two characters. The pivot year is the starting year of the 100-year range in which a two-character date string year resides. The default pivot year is the current year minus 50 years.

The syntax for entering a pivot year is:

newString = datestr(oldString, fieldSpec, pivotYear);

This example changes the pivot year. Note the effect on the output:

datestr('4/16/55', 1, 1900)
ans =
   16-Apr-1955

datestr('4/16/55', 1, 2000)
ans =
   16-Apr-2055

Date Vectors vs. Vectors of Date Numbers

A six-element vector could represent either a single date vector, or a vector of six individual serial date numbers. For example, the vector [2010 12 15 11 45 03] could represent either 11:45:03 on December 15, 2010 or a vector of serial date numbers 2010, 12, 15, and so on.

If you are working with a date vector that the date conversion functions interpret by default as a vector of serial date numbers, you might need to explicitly convert your vector to a date number first, and then convert the value returned by datenum to the desired format.

In this example, the year 3000 is beyond the range of years for which MATLAB defaults to date vector format. Because of this, the intended format of the input vector is unclear to the datestr function, and the input is considered to be a vector of date numbers:

datestr([3000 11 05 10 32 56])
ans =
    18-Mar-0008
    11-Jan-0000
    05-Jan-0000
    10-Jan-0000
    01-Feb-0000
    25-Feb-0000

If it is your intention that the input is a date vector instead, convert it to a date number first, and then to a date string:

dn = datenum([3000 11 05 10 32 56]);
ds = datestr(dn)
ds =
    05-Nov-3000 10:32:56

Function Summary

MATLAB provides the following functions for time and date handling.

Current Date and Time Functions

Function

Description

clock

Return the current date and time as a date vector

date

Return the current date as date string

now

Return the current date and time as serial date number

Conversion Functions

Function

Description

datenum

Convert to a serial date number

datestr

Convert to a string representation of the date

datevec

Convert to a date vector

Utility Functions

Function

Description

addtodate

Modify a date number by field

calendar

Return a matrix representing a calendar

datetick

Label axis tick lines with dates

eomday

Return the last day of a year and month

weekday

Return the current day of the week

Timing Measurement Functions

Function

Description

cputime

Return the total CPU time used by MATLAB since it was started

etime

Return the time elapsed between two date vectors

tic, toc

Measure the time elapsed between invoking tic and toc

  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.

 © 1984-2012- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS