{"id":1092,"date":"2015-02-12T08:24:42","date_gmt":"2015-02-12T13:24:42","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/?p=1092"},"modified":"2015-02-11T07:30:22","modified_gmt":"2015-02-11T12:30:22","slug":"introduction-to-the-new-matlab-data-types-for-dates-and-time","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2015\/02\/12\/introduction-to-the-new-matlab-data-types-for-dates-and-time\/","title":{"rendered":"Introduction to the New MATLAB Data Types for Dates and Time"},"content":{"rendered":"<div class=\"content\"><!--introduction--><p>Today I'd like to introduce a guest blogger, Andrea Ho, who works for the MATLAB Documentation team here at MathWorks. Today, Andrea will discuss three new data types for representing dates and times in MATLAB in R2014b - <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/datetime.html\"><tt>datetime<\/tt><\/a>, <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/duration.html\"><tt>duration<\/tt><\/a>, and <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/calendarduration.html\"><tt>calendarDuration<\/tt><\/a>.<\/p><!--\/introduction--><h3>Contents<\/h3><div><ul><li><a href=\"#304983c1-de67-4153-88a8-cfa920c0d4a0\">Why New Data Types?<\/a><\/li><li><a href=\"#736cd8f2-e72b-40da-a2e8-63e8a68a8bbc\"><tt>datetime<\/tt> for Points in Time<\/a><\/li><li><a href=\"#2bec0d8e-1ba0-4e0b-a5aa-5ead3022014c\">Example: Calculate Driving Time<\/a><\/li><li><a href=\"#3f0d5e9c-109d-4936-a5b3-cccf72f72b02\">Example: Verify Payment Schedule<\/a><\/li><li><a href=\"#ceae6afd-0928-42b3-b9ab-5f86bda4d2cd\">What Else?<\/a><\/li><li><a href=\"#47b493e4-e363-4ec2-97cd-a41c07d135c4\">Your Thoughts?<\/a><\/li><\/ul><\/div><h4>Why New Data Types?<a name=\"304983c1-de67-4153-88a8-cfa920c0d4a0\"><\/a><\/h4><p>Dates and times are frequently a critical part of data analysis. If they are part of your work, you've likely encountered some of the following limitations of date numbers, date vectors, and date strings:<\/p><div><ul><li>Serial date numbers are useful for numeric calculations, but they are difficult to interpret or debug.<\/li><li>Date vectors and strings clearly communicate dates and times in a human-readable format, but they are not useful for calculations and comparisons.<\/li><li>Date numbers, date vectors, and strings that represent both points in time and lengths of time (elapsed time) are confusing. For example, does the date vector <tt>[2015 1 1 0 0 0]<\/tt> represent January 1, 2015 at midnight, or an elapsed time of 2015 years, 1 month, and 1 day?<\/li><\/ul><\/div><p>Starting in R2014b, <tt>datetime<\/tt>, <tt>duration<\/tt>, and <tt>calendarDuration<\/tt> are data types dedicated to storing date and time data, and are easily distinguishable from numeric values. The three types differentiate between points in time, elapsed time in units of constant length (such as hours, minutes, and seconds), and elapsed time in units of flexible length (such as weeks and months). <tt>datetime<\/tt>, <tt>duration<\/tt>, and <tt>calendarDuration<\/tt> represent dates and times in a way that is easy to read, is suitable for computations, has much higher precision (up to nanosecond precision), and is more memory-efficient. With the new data types, you won't have to maintain or convert between different representations of the same date and time value. Work with <tt>datetime<\/tt>, <tt>duration<\/tt>, and <tt>calendarDuration<\/tt> much like you do with numeric types like <tt>double<\/tt>, using standard array operations.<\/p><p>Let's see the new data types in action.<\/p><h4><tt>datetime<\/tt> for Points in Time<a name=\"736cd8f2-e72b-40da-a2e8-63e8a68a8bbc\"><\/a><\/h4><p>The <tt>datetime<\/tt> data type represents absolute points in time such as January 1, 2015 at midnight. The <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/datetime.html\"><tt>datetime<\/tt><\/a> function can create a <tt>datetime<\/tt> variable from the current date and time:<\/p><pre class=\"codeinput\">t0 = datetime(<span class=\"string\">'now'<\/span>)\r\n<\/pre><pre class=\"codeoutput\">t0 = \r\n   16-Jan-2015 16:24:30\r\n<\/pre><p>or from numeric inputs:<\/p><pre class=\"codeinput\">t0 = datetime(2015,1,1,2,3,4)\r\n<\/pre><pre class=\"codeoutput\">t0 = \r\n   01-Jan-2015 02:03:04\r\n<\/pre><pre class=\"codeinput\">whos <span class=\"string\">t0<\/span>\r\n<\/pre><pre class=\"codeoutput\">  Name      Size            Bytes  Class       Attributes\r\n\r\n  t0        1x1               121  datetime              \r\n\r\n<\/pre><p>If you are interested only in the time portion of <tt>t0<\/tt>, you can display just that.<\/p><pre class=\"codeinput\">t0.Format = <span class=\"string\">'HH:mm'<\/span>\r\n<\/pre><pre class=\"codeoutput\">t0 = \r\n   02:03\r\n<\/pre><p>Changing the format of a datetime variable affects how it is displayed, but not its numeric value. Though you can no longer see the year, month and day values, that information is still stored in the variable. Let's turn the display of the date portion of <tt>t0<\/tt> back on.<\/p><pre class=\"codeinput\">t0.Format = <span class=\"string\">'dd-MMM-yyyy HH:mm'<\/span>\r\n<\/pre><pre class=\"codeoutput\">t0 = \r\n   01-Jan-2015 02:03\r\n<\/pre><p>By changing the display format, you can view the value of a <tt>datetime<\/tt> variable with up to nanosecond precision!<\/p><pre class=\"codeinput\">t0.Format = <span class=\"string\">'dd-MMM-yyyy HH:mm:ss.SSSSSSSSS'<\/span>\r\n<\/pre><pre class=\"codeoutput\">t0 = \r\n   01-Jan-2015 02:03:04.000000000\r\n<\/pre><p>If you are a frequent user of date string formats, you'll recognize that some of the format specifiers for <tt>datetime<\/tt> are different from those for the <tt>datestr<\/tt>, <tt>datenum<\/tt>, and <tt>datevec<\/tt> functions.. The new format syntax allows for more options and is now consistent with the <a href=\"http:\/\/www.unicode.org\/reports\/tr35\/tr35-dates.html#Date_Field_Symbol_Table\">Unicode Locale Data Markup Language (LDML) standard<\/a>.<\/p><h4>Example: Calculate Driving Time<a name=\"2bec0d8e-1ba0-4e0b-a5aa-5ead3022014c\"><\/a><\/h4><p>The <tt>duration<\/tt> data type represents the exact difference between two specific points in time. Suppose you drove overnight, leaving your home on January 1, 2015 at 11 PM, and arriving at your destination at 4:30 AM the next day. How much time did you spend on the road? (Ignore the possibility of crossing into another time zone; we'll see how <tt>datetime<\/tt> manages time zones in a <a href=\"https:\/\/blogs.mathworks.com\/loren\/2015\/03\/11\/matlab-data-types-for-dates-and-time-part-ii\"> future post<\/a>.)<\/p><pre class=\"codeinput\">t0 = datetime(2015,1,1,23,0,0);\r\nt1 = datetime(2015,1,2,4,30,0);\r\ndt = t1-t0\r\n<\/pre><pre class=\"codeoutput\">dt = \r\n   05:30:00\r\n<\/pre><p><tt>dt<\/tt> is a <tt>duration<\/tt> variable displayed as hours:minutes:seconds. Like <tt>datetime<\/tt>, a duration behaves mostly like a numeric value but displays in a format that shows time well. Let's change the format to view <tt>dt<\/tt> as a number of minutes.<\/p><pre class=\"codeinput\">dt.Format = <span class=\"string\">'m'<\/span>\r\n<\/pre><pre class=\"codeoutput\">dt = \r\n   330 mins\r\n<\/pre><p>We can perform common arithmetic operations on date and time variables. Even though <tt>dt<\/tt> is currently displayed as a number of minutes, we can add or subtract a duration in any unit, including hours and seconds.<\/p><pre class=\"codeinput\">dt2 = dt - hours(1) + seconds(5)\r\n<\/pre><pre class=\"codeoutput\">dt2 = \r\n   270.08 mins\r\n<\/pre><h4>Example: Verify Payment Schedule<a name=\"3f0d5e9c-109d-4936-a5b3-cccf72f72b02\"><\/a><\/h4><p>Suppose you opened a bank account on January 1, 2014. The account pays interest monthly on the last day of each month. Let's find the first date on which interest was paid. Is there a solution that does not depend on the account opening date? The <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/dateshift.html\"><tt>dateshift<\/tt><\/a> function is useful for shifting dates to the start or end of a unit of time. In our case, we will shift the account opening date to the end of the month.<\/p><pre class=\"codeinput\">t0 = datetime(2014,1,1);\r\nt1 = dateshift(t0,<span class=\"string\">'end'<\/span>,<span class=\"string\">'month'<\/span>)\r\n<\/pre><pre class=\"codeoutput\">t1 = \r\n   31-Jan-2014\r\n<\/pre><p>Suppose our records indicate that we received interest payments at noon. We can add this information to <tt>t1<\/tt> by modifying its <tt>Hour<\/tt> property.<\/p><pre class=\"codeinput\">t1.Hour = 12;\r\n<\/pre><p>Now let's create a sequence of dates to represent the next 12 payment dates. What happens if we add increments of 30 days to <tt>t1<\/tt>?<\/p><pre class=\"codeinput\">t = t1 + days(0:30:335)'\r\n<\/pre><pre class=\"codeoutput\">t = \r\n   31-Jan-2014 12:00:00\r\n   02-Mar-2014 12:00:00\r\n   01-Apr-2014 12:00:00\r\n   01-May-2014 12:00:00\r\n   31-May-2014 12:00:00\r\n   30-Jun-2014 12:00:00\r\n   30-Jul-2014 12:00:00\r\n   29-Aug-2014 12:00:00\r\n   28-Sep-2014 12:00:00\r\n   28-Oct-2014 12:00:00\r\n   27-Nov-2014 12:00:00\r\n   27-Dec-2014 12:00:00\r\n<\/pre><p>Yikes, most of these dates don't fall on the last day of the month. A <tt>duration<\/tt> of 30 days, with each day being exactly 24 hours long, was not the correct step size to use. The correct step size depends on the month, since some months have 30 days, while others have 31 (or perhaps 28, or 29). What we really want to do is add a series of <i>calendar months<\/i> to <tt>t1<\/tt>.<\/p><pre class=\"codeinput\">t = t1 + calmonths(0:11)'\r\n<\/pre><pre class=\"codeoutput\">t = \r\n   31-Jan-2014\r\n   28-Feb-2014\r\n   31-Mar-2014\r\n   30-Apr-2014\r\n   31-May-2014\r\n   30-Jun-2014\r\n   31-Jul-2014\r\n   31-Aug-2014\r\n   30-Sep-2014\r\n   31-Oct-2014\r\n   30-Nov-2014\r\n   31-Dec-2014\r\n<\/pre><p>The <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/calmonths.html\"><tt>calmonths<\/tt><\/a> function creates a <tt>calendarDuration<\/tt> array containing calendar months. A <tt>calendarDuration<\/tt> value represents a flexible or non-constant amount of time such as 1 month. There is no way to know exactly how many days, hours, minutes, or seconds there are in 1 month without knowing which month of the year I am referring to. The length of a calendar month is unknown until you relate it to a specific point in time.<\/p><p>How many days are between each of the payment dates?<\/p><pre class=\"codeinput\">dt = caldiff(t,<span class=\"string\">'days'<\/span>)\r\n<\/pre><pre class=\"codeoutput\">dt = \r\n   28d\r\n   31d\r\n   30d\r\n   31d\r\n   30d\r\n   31d\r\n   31d\r\n   30d\r\n   31d\r\n   30d\r\n   31d\r\n<\/pre><p>Each incremental calendar month represents a different number of days.<\/p><p>Our bank sent us a file named <tt>interest.txt<\/tt> that contains interest amounts for each month of the year. We can import this data interactively using the <a href=\"\">Import Tool<\/a>.<\/p><p><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/loren\/2015\/ImportTool2.png\" alt=\"\"> <\/p><p>Alternatively, we can use the <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/readtable.html\"><tt>readtable<\/tt><\/a> and <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/textscan.html\"><tt>textscan<\/tt><\/a> functions to read the file programmatically. Use the <tt>%D<\/tt> specifier to read a date or time string and specify the string format within curly braces.<\/p><pre class=\"codeinput\">T = readtable(<span class=\"string\">'interest.txt'<\/span>,<span class=\"string\">'Format'<\/span>,<span class=\"string\">'%{dd MMMM yyyy HH:mm}D %f'<\/span>)\r\n<\/pre><pre class=\"codeoutput\">T = \r\n             Date              Interest\r\n    _______________________    ________\r\n    31 January 2014 12:00      1.93    \r\n    28 February 2014 12:00     4.28    \r\n    31 March 2014 12:00        4.82    \r\n    30 April 2014 12:00        1.23    \r\n    31 May 2014 12:00          5.89    \r\n    30 June 2014 12:00         2.26    \r\n    31 July 2014 12:00         3.84    \r\n    31 August 2014 12:00       5.82    \r\n    30 September 2014 12:00    2.51    \r\n    31 October 2014 12:00      2.99    \r\n    30 November 2014 12:00     6.17    \r\n    31 December 2014 12:00     2.65    \r\n<\/pre><p>Even though the text file contains strings, the values in the <tt>Date<\/tt> column of the table are not strings. They are <tt>datetime<\/tt> values.<\/p><p>If we compare our payment times with the bank's data, we'll see that they are the same.<\/p><pre class=\"codeinput\">isequal(t,T.Date)\r\n<\/pre><pre class=\"codeoutput\">ans =\r\n     1\r\n<\/pre><p>Now let's calculate the cumulative interest at the end of each month and plot the data. When using <tt>plot<\/tt>, working with <tt>datetime<\/tt> is much easier than working with serial date numbers.<\/p><pre class=\"codeinput\">c_payments = cumsum(T.Interest);\r\nfigure\r\nplot(T.Date,c_payments)\r\nxlabel(<span class=\"string\">'Date'<\/span>)\r\nylabel(<span class=\"string\">'Cummulative Interest Payments'<\/span>)\r\n<\/pre><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/loren\/2015\/datetimePart1_01.png\" alt=\"\"> <p>The date axis is automatically labeled with date strings that are easy to understand. You no longer have to call <tt>datetick<\/tt> to do this! If we want to change the format of the dates, we can specify the desired format of the axis ticks in the call to <tt>plot<\/tt>.<\/p><pre class=\"codeinput\">figure\r\nplot(T.Date,c_payments,<span class=\"string\">'DatetimeTickFormat'<\/span>,<span class=\"string\">'MMMM'<\/span>)\r\nxlabel(<span class=\"string\">'Date'<\/span>)\r\nylabel(<span class=\"string\">'Cummulative Interest Payments'<\/span>)\r\nax = gca;\r\nax.XTickLabelRotation = -15;\r\n<\/pre><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/loren\/2015\/datetimePart1_02.png\" alt=\"\"> <p>To create charts containing date and time values using other plotting functions, you still need to work with serial date numbers for the time being. We recognize that this is inconvenient and we are planning improvements. You can learn more <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/matlab_prog\/plot-dates-and-durations.html\">here<\/a> about how to plot <tt>datetime<\/tt> and <tt>duration<\/tt> values.<\/p><h4>What Else?<a name=\"ceae6afd-0928-42b3-b9ab-5f86bda4d2cd\"><\/a><\/h4><p>Notice that in our analysis of travel times and interest payments, there was no need to use serial date numbers, date vectors, or strings at all. <tt>datetime<\/tt>, <tt>duration<\/tt>, and <tt>calendarDuration<\/tt> allow you to manipulate dates and times quickly and more intuitively. The new data types are intended as a replacement for <tt>datenum<\/tt>, <tt>datevec<\/tt>, and <tt>datestr<\/tt>. However, these older functions will continue to exist in MATLAB for the foreseeable future because we know that many people rely on them in existing code.<\/p><p>In a future post, I'll show how <tt>datetime<\/tt>, <tt>duration<\/tt>, and <tt>calendarDuration<\/tt> allow you to work with time zones, daylight saving time, and dates in languages other than English.<\/p><h4>Your Thoughts?<a name=\"47b493e4-e363-4ec2-97cd-a41c07d135c4\"><\/a><\/h4><p>Do you see yourself using the new date and time data types with your data?  Let us know by leaving a comment <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=1092#respond\">here<\/a>.<\/p><script language=\"JavaScript\"> <!-- \r\n    function grabCode_424f746bcfc74e1684ab31b87267c89a() {\r\n        \/\/ Remember the title so we can use it in the new page\r\n        title = document.title;\r\n\r\n        \/\/ Break up these strings so that their presence\r\n        \/\/ in the Javascript doesn't mess up the search for\r\n        \/\/ the MATLAB code.\r\n        t1='424f746bcfc74e1684ab31b87267c89a ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 424f746bcfc74e1684ab31b87267c89a';\r\n    \r\n        b=document.getElementsByTagName('body')[0];\r\n        i1=b.innerHTML.indexOf(t1)+t1.length;\r\n        i2=b.innerHTML.indexOf(t2);\r\n \r\n        code_string = b.innerHTML.substring(i1, i2);\r\n        code_string = code_string.replace(\/REPLACE_WITH_DASH_DASH\/g,'--');\r\n\r\n        \/\/ Use \/x3C\/g instead of the less-than character to avoid errors \r\n        \/\/ in the XML parser.\r\n        \/\/ Use '\\x26#60;' instead of '<' so that the XML parser\r\n        \/\/ doesn't go ahead and substitute the less-than character. \r\n        code_string = code_string.replace(\/\\x3C\/g, '\\x26#60;');\r\n\r\n        copyright = 'Copyright 2015 The MathWorks, Inc.';\r\n\r\n        w = window.open();\r\n        d = w.document;\r\n        d.write('<pre>\\n');\r\n        d.write(code_string);\r\n\r\n        \/\/ Add copyright line at the bottom if specified.\r\n        if (copyright.length > 0) {\r\n            d.writeln('');\r\n            d.writeln('%%');\r\n            if (copyright.length > 0) {\r\n                d.writeln('% _' + copyright + '_');\r\n            }\r\n        }\r\n\r\n        d.write('<\/pre>\\n');\r\n\r\n        d.title = title + ' (MATLAB code)';\r\n        d.close();\r\n    }   \r\n     --> <\/script><p style=\"text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray\"><br><a href=\"javascript:grabCode_424f746bcfc74e1684ab31b87267c89a()\"><span style=\"font-size: x-small;        font-style: italic;\">Get \r\n      the MATLAB code <noscript>(requires JavaScript)<\/noscript><\/span><\/a><br><br>\r\n      Published with MATLAB&reg; R2014b<br><\/p><\/div><!--\r\n424f746bcfc74e1684ab31b87267c89a ##### SOURCE BEGIN #####\r\n%% Introduction to the New MATLAB Data Types for Dates and Time\r\n% Today I'd like to introduce a guest blogger, Andrea Ho, who works for the\r\n% MATLAB Documentation team here at MathWorks. Today, Andrea will discuss three new data types for representing dates\r\n% and times in MATLAB in R2014b -\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/datetime.html |datetime|>,\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/duration.html |duration|>, and\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/calendarduration.html\r\n% |calendarDuration|>.\r\n%\r\n%% Why New Data Types?\r\n% Dates and times are frequently a critical part of data analysis. If they\r\n% are part of your work, you've likely encountered some of the following\r\n% limitations of date numbers, date vectors, and date strings:\r\n%\r\n% * Serial date numbers are useful for numeric calculations, but they \r\n% are difficult to interpret or debug. \r\n% * Date vectors and strings clearly communicate dates and times in a\r\n% human-readable format, but they are not useful for calculations and\r\n% comparisons.\r\n% * Date numbers, date vectors, and strings that represent both points in time\r\n% and lengths of time (elapsed time) are confusing. For example,\r\n% does the date vector |[2015 1 1 0 0 0]| represent January 1, 2015 at\r\n% midnight, or an elapsed time of 2015 years, 1 month, and 1 day?\r\n%\r\n% Starting in R2014b, |datetime|, |duration|, and |calendarDuration| are\r\n% data types dedicated to storing date and time data, and are easily\r\n% distinguishable from numeric values. The three types differentiate\r\n% between points in time, elapsed time in\r\n% units of constant length (such as hours, minutes, and seconds), and elapsed\r\n% time in units of flexible length (such as weeks and months). |datetime|,\r\n% |duration|, and |calendarDuration| represent dates and times in a way\r\n% that is easy to read, is suitable for computations, has much higher\r\n% precision (up to nanosecond precision), and is more memory-efficient.\r\n% With the new data types, you won't have to\r\n% maintain or convert between different representations of the same date\r\n% and time value. Work with |datetime|, |duration|, and |calendarDuration|\r\n% much like you do with numeric types like |double|, using standard array\r\n% operations.\r\n%\r\n% Let's see the new data types in action.\r\n%% |datetime| for Points in Time\r\n% The |datetime| data type represents absolute points in time such as January 1,\r\n% 2015 at midnight. The\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/datetime.html |datetime|>\r\n% function can create a |datetime| variable from the current date and time:\r\nt0 = datetime('now')\r\n%%\r\n% or from numeric inputs:\r\nt0 = datetime(2015,1,1,2,3,4)\r\n%%\r\nwhos t0\r\n%%\r\n% If you are interested only in the time portion of |t0|, you can display\r\n% just that. \r\nt0.Format = 'HH:mm'\r\n%%\r\n% Changing the format of a datetime variable affects how it is displayed,\r\n% but not its numeric value. Though you can no longer see the year, month and day values, that information is still stored in the\r\n% variable. Let's turn the display of the date portion of |t0| back on.\r\nt0.Format = 'dd-MMM-yyyy HH:mm'\r\n%%\r\n% By changing the display format, you can view the value of a |datetime| variable with up to nanosecond precision!\r\nt0.Format = 'dd-MMM-yyyy HH:mm:ss.SSSSSSSSS'\r\n%%\r\n% If you are a frequent user of date string formats, you'll recognize that some of the\r\n% format specifiers for |datetime| are different from those for the |datestr|, |datenum|, and |datevec| functions.. The new format syntax\r\n% allows for more options and is now consistent with the\r\n% <http:\/\/www.unicode.org\/reports\/tr35\/tr35-dates.html#Date_Field_Symbol_Table\r\n% Unicode Locale Data Markup Language (LDML) standard>.\r\n%% Example: Calculate Driving Time\r\n% The |duration| data type represents the exact difference between two specific\r\n% points in time. Suppose you drove overnight, leaving your home on January\r\n% 1, 2015 at 11 PM, and arriving at your destination at 4:30 AM the next\r\n% day. How much time did you spend on the road? (Ignore the possibility of\r\n% crossing into another time zone; we'll see how |datetime| manages time zones in\r\n% a future post.)\r\n%\r\nt0 = datetime(2015,1,1,23,0,0);\r\nt1 = datetime(2015,1,2,4,30,0);\r\ndt = t1-t0\r\n%%\r\n% |dt| is a |duration| variable displayed as\r\n% hours:minutes:seconds. Like |datetime|, a duration behaves mostly like a\r\n% numeric value but displays in a format that shows time well. Let's change\r\n% the format to view |dt| as a number of minutes.\r\ndt.Format = 'm'\r\n%%\r\n% We can perform common arithmetic operations on date and time variables.\r\n% Even though |dt| is currently displayed as a number of minutes, we can\r\n% add or subtract a duration in any unit, including hours and seconds.\r\ndt2 = dt - hours(1) + seconds(5)\r\n\r\n\r\n%% Example: Verify Payment Schedule\r\n%% \r\n% Suppose you opened a bank account on January 1, 2014. The account pays interest\r\n% monthly on the last day of each month. Let's find the first date on which\r\n% interest was paid. Is there a solution that does not depend\r\n% on the account opening date? The\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/dateshift.html |dateshift|>\r\n% function is useful for shifting dates to the start or end of a unit of\r\n% time. In our case, we will shift the account opening date to the end of the month.\r\nt0 = datetime(2014,1,1);\r\nt1 = dateshift(t0,'end','month')\r\n%%\r\n% Suppose our records indicate that we received interest payments at noon.\r\n% We can add this information to |t1| by modifying its |Hour| property.\r\nt1.Hour = 12;\r\n%%\r\n% Now let's create a sequence of dates to represent the next 12 payment\r\n% dates. What happens if we add increments of 30 days to |t1|? \r\nt = t1 + days(0:30:335)'\r\n%%\r\n% Yikes, most of these dates don't fall on the last day of the month. A\r\n% |duration| of 30 days, with each day being exactly 24 hours long, was not the correct step size to use.\r\n% The correct step size depends on the month, since some\r\n% months have 30 days, while others have 31 (or perhaps 28, or 29). What we\r\n% really want to do is add a series of _calendar months_ to |t1|. \r\nt = t1 + calmonths(0:11)'\r\n%%\r\n% The <https:\/\/www.mathworks.com\/help\/matlab\/ref\/calmonths.html |calmonths|> function creates a |calendarDuration| array containing\r\n% calendar months. A |calendarDuration| value represents a flexible or non-constant amount\r\n% of time such as 1 month. There is no way to know exactly how many\r\n% days, hours, minutes, or seconds there are in 1 month without knowing\r\n% which month of the year I am referring to. The length of a calendar month is unknown until you relate it to a\r\n% specific point in time.\r\n\r\n%%\r\n% How many days are between each of the payment dates?\r\ndt = caldiff(t,'days')\r\n%%\r\n% Each incremental calendar month represents a different number of days.\r\n%%\r\n% Our bank sent us a file named |interest.txt|\r\n% that contains interest amounts for each month of the year. \r\n% We can import this data interactively using the\r\n% <\r\n% Import Tool>.\r\n%%\r\n%\r\n% <<ImportTool2.png>>\r\n%\r\n%%\r\n% Alternatively, we can use the\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/readtable.html |readtable|> and\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/textscan.html |textscan|>\r\n% functions to read the file programmatically. Use the |%D| specifier to\r\n% read a date or time string and specify the string format within curly braces.\r\nT = readtable('interest.txt','Format','%{dd MMMM yyyy HH:mm}D %f')\r\n%%\r\n% Even though the text file contains strings, the values in the |Date|\r\n% column of the table are not strings. They are |datetime| values.\r\n%%\r\n% If we compare our payment times with the bank's data, we'll see that\r\n% they are the same.\r\nisequal(t,T.Date)\r\n%% \r\n% Now let's calculate the cumulative interest at the end of each month and plot the data. When using |plot|, working with |datetime| is much easier\r\n% than working with serial date numbers.\r\nc_payments = cumsum(T.Interest);\r\nfigure\r\nplot(T.Date,c_payments)\r\nxlabel('Date')\r\nylabel('Cummulative Interest Payments')\r\n%%\r\n% The date axis is automatically labeled with date strings that are easy to\r\n% understand. You no longer have to call |datetick| to do this! If we want to change the format of the dates, we\r\n% can specify the desired format of the axis ticks in the call to |plot|.\r\nfigure\r\nplot(T.Date,c_payments,'DatetimeTickFormat','MMMM')\r\nxlabel('Date')\r\nylabel('Cummulative Interest Payments')\r\nax = gca;\r\nax.XTickLabelRotation = -15;\r\n%%\r\n% To create charts containing date and time values using other plotting\r\n% functions, you still need to work with serial date numbers for the time being. We recognize that\r\n% this is inconvenient and we are planning improvements. You can learn\r\n% more <https:\/\/www.mathworks.com\/help\/matlab\/matlab_prog\/plot-dates-and-durations.html\r\n% here> about how to plot |datetime| and |duration| values.\r\n%% What Else?\r\n% Notice that in our analysis of travel times and interest payments,\r\n% there was no need to use serial date numbers, date vectors, or strings at\r\n% all. |datetime|, |duration|, and |calendarDuration| allow you to manipulate\r\n% dates and times quickly and more intuitively. \r\n% The new data types are intended as a replacement for |datenum|,\r\n% |datevec|, and |datestr|. However, these older functions will continue to exist in\r\n% MATLAB for the foreseeable future because we know that many people rely on\r\n% them in existing code. \r\n% \r\n% In a future post, I'll show how\r\n% |datetime|, |duration|, and |calendarDuration| allow you to work with\r\n% time zones, daylight saving time, and dates in languages other than English.\r\n%% Your Thoughts?\r\n% Do you see yourself using the new date and time data types with your\r\n% data?  Let us know\r\n% by leaving a comment\r\n% <https:\/\/blogs.mathworks.com\/loren\/?p=1092#respond here>.\r\n##### SOURCE END ##### 424f746bcfc74e1684ab31b87267c89a\r\n-->","protected":false},"excerpt":{"rendered":"<div class=\"overview-image\"><img decoding=\"async\"  class=\"img-responsive\" src=\"https:\/\/blogs.mathworks.com\/images\/loren\/2015\/datetimePart1_02.png\" onError=\"this.style.display ='none';\" \/><\/div><!--introduction--><p>Today I'd like to introduce a guest blogger, Andrea Ho, who works for the MATLAB Documentation team here at MathWorks. Today, Andrea will discuss three new data types for representing dates and times in MATLAB in R2014b - <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/datetime.html\"><tt>datetime<\/tt><\/a>, <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/duration.html\"><tt>duration<\/tt><\/a>, and <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/calendarduration.html\"><tt>calendarDuration<\/tt><\/a>.... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2015\/02\/12\/introduction-to-the-new-matlab-data-types-for-dates-and-time\/\">read more >><\/a><\/p>","protected":false},"author":39,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[57,6,1],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/1092"}],"collection":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/users\/39"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/comments?post=1092"}],"version-history":[{"count":4,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/1092\/revisions"}],"predecessor-version":[{"id":1114,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/1092\/revisions\/1114"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=1092"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=1092"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=1092"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}