{"id":504,"date":"2011-11-28T17:49:07","date_gmt":"2011-11-28T17:49:07","guid":{"rendered":"https:\/\/blogs.mathworks.com\/desktop\/2011\/11\/28\/using-dates-in-matlab\/"},"modified":"2011-11-28T17:49:07","modified_gmt":"2011-11-28T17:49:07","slug":"using-dates-in-matlab","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/community\/2011\/11\/28\/using-dates-in-matlab\/","title":{"rendered":"Using Dates in MATLAB"},"content":{"rendered":"<p>Three weeks ago I wrote about MATLAB's new spreadsheet import tool. Since then I've had a few conversations regarding using dates in MATLAB; dates are common as column headers or table data. The import tool will turn Excel dates into MATLAB <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2011b\/techdoc\/ref\/datenum.html\"><tt>datenum<\/tt><\/a>s. A datenum in MATLAB is just a double that represents any date & time after midnight Jan 1, 0000 AD. MATLAB comes with several useful functions for handling these special case numbers, and in particular for displaying them.<\/p>\n<p>The <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2011b\/techdoc\/ref\/now.html\"><tt>now<\/tt><\/a>, <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2011b\/techdoc\/ref\/clock.html\"><tt>clock<\/tt><\/a>, and <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2011b\/techdoc\/ref\/date.html\"><tt>date<\/tt><\/a> functions will provide the current date & time as a <tt>datenum<\/tt>, <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2011b\/techdoc\/ref\/datevec.html\"><tt>datevec<\/tt><\/a>, or <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2011b\/techdoc\/ref\/datestr.html\"><tt>detestr<\/tt><\/a>, respectively. While a datenum is a single number representing the date and time, a datevec splits the year, month, day, hour, minute, and second components out in 1x6 vector. A datestr is the string representation of a date time. There are a ton formatting options available for how the date and time are displayed (see below).<\/p>\n<pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">currentTimeAndDate = now\r\ncurrentTimeAndDateAsVector = clock\r\ncurrentDateAsString = date<\/pre>\n<pre style=\"font-style:oblique\">\r\ncurrentTimeAndDate =\r\n\r\n   7.3484e+05\r\n\r\n\r\ncurrentTimeAndDateAsVector =\r\n\r\n         2011           11           28            8           50       20.486\r\n\r\n\r\ncurrentDateAsString =\r\n\r\n28-Nov-2011\r\n\r\n<\/pre>\n<p>As far as the data is concerned, these three date types are interchangeable using the conversion functions. You can use the <tt>datenum<\/tt>, <tt>datevec<\/tt>, and <tt>datestr<\/tt> functions to convert between the three types. Individual functions that perform calculations on dates usually prefer a particular format, for example <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2011b\/techdoc\/ref\/addtodate.html\"><tt>addtodate<\/tt><\/a> looks for datenum types.<\/p>\n<pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">currentDateAsNumber = datenum(currentDateAsString)\r\ncurrentDateAndDtimeAsNumber = datenum(currentTimeAndDate) <span style=\"color: #228B22\">%note the difference from above<\/span>\r\ncurrentDate = datestr(currentTimeAndDate)\r\ncurrentDateAsVector = datevec(currentDateAsString)<\/pre>\n<pre style=\"font-style:oblique\">\r\ncurrentDateAsNumber =\r\n\r\n      734835\r\n\r\n\r\ncurrentDateAndDtimeAsNumber =\r\n\r\n   7.3484e+05\r\n\r\n\r\ncurrentDate =\r\n\r\n28-Nov-2011 08:50:20\r\n\r\n\r\ncurrentDateAsVector =\r\n\r\n        2011          11          28           0           0           0\r\n\r\n<\/pre>\n<p>The usage of dates I'm particularly interested in is with plots. Let's say we have some time-varying data and we want the x-axis to reflect those dates. If I just plot the data against the datenum, by default the x-labels will all be large, ugly numbers. <\/p>\n<pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">firstInMonths = repmat([2011 1 1 0 0 0],12,1);\r\nfirstInMonths(:,2) = 1:12;\r\nbar(datenum(firstInMonths),rand(1,12)*10)<\/pre>\n<div align=\"center\">\n<img decoding=\"async\" border=\"0\" src=\"https:\/\/blogs.mathworks.com\/images\/desktop\/michael_katz_dates\/dates_01.png\" alt=\"Random Date Data\">\n<\/div>\n<p>Thankfully, MATLAB comes with a simple function, <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2011b\/techdoc\/ref\/datetick.html\"><tt>datetick<\/tt><\/a>, for turning those numbers into strings:<\/p>\n<pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">datetick<\/pre>\n<div align=\"center\">\n<img decoding=\"async\" border=\"0\" src=\"https:\/\/blogs.mathworks.com\/images\/desktop\/michael_katz_dates\/dates_02.png\" alt=\"Random Date Data With Ticks\">\n<\/div>\n<p>Unfortunately, those tick labels aren't very pretty. Let's use a date format with the <tt>datetick<\/tt> function to specify how we want labels to look. For this function, we can use any date format recognized by the <tt>detestr<\/tt> function (see below).<\/p>\n<pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">datetick(<span style=\"color: #A020F0\">'x'<\/span>,<span style=\"color: #A020F0\">'mmm-yy'<\/span>)<\/pre>\n<div align=\"center\">\n<img decoding=\"async\" border=\"0\" src=\"https:\/\/blogs.mathworks.com\/images\/desktop\/michael_katz_dates\/dates_03.png\" alt=\"Random Date Data with well-formatted ticks\">\n<\/div>\n<p>Finally, for your reference, here is the help information for <tt>datestr<\/tt>, which lists how to formate a date string:<\/p>\n<pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">help <span style=\"color: #A020F0\">datestr<\/span><\/pre>\n<pre style=\"font-style:oblique\"> DATESTR String representation of date.\r\n    S = DATESTR(V) converts one or more date vectors V to date strings S.\r\n    Input V must be an M-by-6 matrix containing M full (six-element) date\r\n    vectors. Each element of V must be a positive double-precision number.\r\n    DATESTR returns a column vector of M date strings, where M is the total\r\n    number of date vectors in V. \r\n \r\n    S = DATESTR(N) converts one or more serial date numbers N to date\r\n    strings S. Input argument N can be a scalar, vector, or\r\n    multidimensional array of positive double-precision numbers. DATESTR\r\n    returns a column vector of M date strings, where M is the total number\r\n    of date numbers in N. \r\n \r\n    S = DATESTR(D, F) converts one or more date vectors, serial date\r\n    numbers, or date strings D into the same number of date strings S.\r\n    Input argument F is a format number or string that determines the\r\n    format of the date string output. Valid values for F are given in Table\r\n    1, below. Input F may also contain a free-form date format string\r\n    consisting of format tokens as shown in Table 2, below. \r\n \r\n    Date strings with 2-character years are interpreted to be within the\r\n    100 years centered around the current year. \r\n \r\n    S = DATESTR(S1, F, P) converts date string S1 to date string S,\r\n    applying format F to the output string, and using pivot year P as the\r\n    starting year of the 100-year range in which a two-character year\r\n    resides. The default pivot year is the current year minus 50 years.\r\n    F = -1 uses the default format.\r\n \r\n \tS = DATESTR(...,'local') returns the string in a localized format. The\r\n \tdefault (which can be called with 'en_US') is US English. This argument \r\n \tmust come last in the argument sequence.\r\n \r\n \tNote:  The vectorized calling syntax can offer significant performance\r\n \timprovement for large arrays.\r\n \r\n \tTable 1: Standard MATLAB Date format definitions\r\n \r\n    Number           String                   Example\r\n    ===========================================================================\r\n       0             'dd-mmm-yyyy HH:MM:SS'   01-Mar-2000 15:45:17 \r\n       1             'dd-mmm-yyyy'            01-Mar-2000  \r\n       2             'mm\/dd\/yy'               03\/01\/00     \r\n       3             'mmm'                    Mar          \r\n       4             'm'                      M            \r\n       5             'mm'                     03            \r\n       6             'mm\/dd'                  03\/01        \r\n       7             'dd'                     01            \r\n       8             'ddd'                    Wed          \r\n       9             'd'                      W            \r\n      10             'yyyy'                   2000         \r\n      11             'yy'                     00           \r\n      12             'mmmyy'                  Mar00        \r\n      13             'HH:MM:SS'               15:45:17     \r\n      14             'HH:MM:SS PM'             3:45:17 PM  \r\n      15             'HH:MM'                  15:45        \r\n      16             'HH:MM PM'                3:45 PM     \r\n      17             'QQ-YY'                  Q1-96        \r\n      18             'QQ'                     Q1           \r\n      19             'dd\/mm'                  01\/03        \r\n      20             'dd\/mm\/yy'               01\/03\/00     \r\n      21             'mmm.dd,yyyy HH:MM:SS'   Mar.01,2000 15:45:17 \r\n      22             'mmm.dd,yyyy'            Mar.01,2000  \r\n      23             'mm\/dd\/yyyy'             03\/01\/2000 \r\n      24             'dd\/mm\/yyyy'             01\/03\/2000 \r\n      25             'yy\/mm\/dd'               00\/03\/01 \r\n      26             'yyyy\/mm\/dd'             2000\/03\/01 \r\n      27             'QQ-YYYY'                Q1-1996        \r\n      28             'mmmyyyy'                Mar2000        \r\n      29 (ISO 8601)  'yyyy-mm-dd'             2000-03-01\r\n      30 (ISO 8601)  'yyyymmddTHHMMSS'        20000301T154517 \r\n      31             'yyyy-mm-dd HH:MM:SS'    2000-03-01 15:45:17 \r\n \r\n    Table 2: Free-form date format symbols\r\n    \r\n    Symbol  Interpretation of format symbol\r\n    ===========================================================================\r\n    yyyy    full year, e.g. 1990, 2000, 2002\r\n    yy      partial year, e.g. 90, 00, 02\r\n    mmmm    full name of the month, according to the calendar locale, e.g.\r\n            \"March\", \"April\" in the UK and USA English locales. \r\n    mmm     first three letters of the month, according to the calendar \r\n            locale, e.g. \"Mar\", \"Apr\" in the UK and USA English locales. \r\n    mm      numeric month of year, padded with leading zeros, e.g. ..\/03\/..\r\n            or ..\/12\/.. \r\n    m       capitalized first letter of the month, according to the\r\n            calendar locale; for backwards compatibility. \r\n    dddd    full name of the weekday, according to the calendar locale, e.g.\r\n            \"Monday\", \"Tuesday\", for the UK and USA calendar locales. \r\n    ddd     first three letters of the weekday, according to the calendar\r\n            locale, e.g. \"Mon\", \"Tue\", for the UK and USA calendar locales. \r\n    dd      numeric day of the month, padded with leading zeros, e.g. \r\n            05\/..\/.. or 20\/..\/.. \r\n    d       capitalized first letter of the weekday; for backwards \r\n            compatibility\r\n    HH      hour of the day, according to the time format. In case the time\r\n            format AM | PM is set, HH does not pad with leading zeros. In \r\n            case AM | PM is not set, display the hour of the day, padded \r\n            with leading zeros. e.g 10:20 PM, which is equivalent to 22:20; \r\n            9:00 AM, which is equivalent to 09:00.\r\n    MM      minutes of the hour, padded with leading zeros, e.g. 10:15, \r\n            10:05, 10:05 AM.\r\n    SS      second of the minute, padded with leading zeros, e.g. 10:15:30,\r\n            10:05:30, 10:05:30 AM. \r\n    FFF     milliseconds field, padded with leading zeros, e.g.\r\n            10:15:30.015.\r\n    PM      set the time format as time of morning or time of afternoon. AM \r\n            or PM is appended to the date string, as appropriate. \r\n \r\n    Examples:\r\n \tDATESTR(now) returns '24-Jan-2003 11:58:15' for that particular date,\r\n \ton an US English locale DATESTR(now,2) returns 01\/24\/03, the same as\r\n \tfor DATESTR(now,'mm\/dd\/yy') DATESTR(now,'dd.mm.yyyy') returns\r\n \t24.01.2003 To convert a non-standard date form into a standard MATLAB\r\n \tdateform, first convert the non-standard date form to a date number,\r\n \tusing DATENUM, for example, \r\n \tDATESTR(DATENUM('24.01.2003','dd.mm.yyyy'),2) returns 01\/24\/03.\r\n \r\n \tSee also DATE, DATENUM, DATEVEC, DATETICK.\r\n\r\n    Reference page in Help browser\r\n       doc datestr\r\n\r\n<\/pre>\n<p>If you're interested in using dates with MATLAB, <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2011b\/techdoc\/ref\/f16-42340.html#f16-32430\">here is a link to the date functions<\/a> that are available.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Three weeks ago I wrote about MATLAB's new spreadsheet import tool. Since then I've had a few conversations regarding using dates in MATLAB; dates are common as column headers or table data. The... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/community\/2011\/11\/28\/using-dates-in-matlab\/\">read more >><\/a><\/p>\n","protected":false},"author":38,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[97,69],"tags":[182,73,183],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/community\/wp-json\/wp\/v2\/posts\/504"}],"collection":[{"href":"https:\/\/blogs.mathworks.com\/community\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.mathworks.com\/community\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/community\/wp-json\/wp\/v2\/users\/38"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/community\/wp-json\/wp\/v2\/comments?post=504"}],"version-history":[{"count":0,"href":"https:\/\/blogs.mathworks.com\/community\/wp-json\/wp\/v2\/posts\/504\/revisions"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/community\/wp-json\/wp\/v2\/media?parent=504"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/community\/wp-json\/wp\/v2\/categories?post=504"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/community\/wp-json\/wp\/v2\/tags?post=504"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}