matlabdatetimefinancial

How to get datetime day, month and year without financial toolbox in Matlab?


I found that functions like day, month and year require Financial Toolbox.

>> [~, packages] = matlab.codetools.requiredFilesAndProducts('month'); packages(2)

ans = 

  struct with fields:

             Name: 'Financial Toolbox'
          Version: '5.8'
    ProductNumber: 30
          Certain: 1

How to know datetime parts without this toolbox?


Solution

  • I don't think that my comments on the question or the accepted solution are getting across in the way I intended, so I'll give a proper answer to better elaborate on what you're seeing.

    There are multiple things called "month" in MATLAB. There is a function called month, that is in the Financial Toolbox (https://www.mathworks.com/help/finance/month.html). There is also a method of the datetime class called "month" (https://www.mathworks.com/help/matlab/ref/month.html). These are two separate functions, and act differently. The regular "month" function (of the Financial Toolbox) will accept any date number or string. However, in MATLAB, if you call "month" and pass it an instance of a datetime (as in the accepted solution's answer, you could use datetime('now')), you will not be calling the Financial Toolbox's function "month", but rather the "month" method of the datetime class, because that is how MATLAB dispatching rules work.

    matlab.codetools.requiredFilesAndProducts does not and cannot know that you're calling "month" with a datetime input, so it can't assume you're calling the datetime method called "month" and instead reports to you the requirements for the Financial Toolbox function.

    If you know you are working with datetimes, you can be more precise in your query to requiredFilesAndProducts:

    >> [~,packages] = matlab.codetools.requiredFilesAndProducts(which('month(datetime(''now''))'))
    
    packages = 
    
             Name: 'MATLAB'
          Version: '8.6'
    ProductNumber: 1
          Certain: 1
    

    By using which('month(datetime(''now''))'), you are more precise by telling the which function exactly what your function call is going to look like (i.e., what its input type will be), which allows it to properly figure out which overloaded "month" will get called and then requiredFilesAndProducts can correctly show you that if your input is a datetime, you only need MATLAB -- not the Financial Toolbox.

    If you truly need to call "month" on a non-datetime, you can effectively get the same behavior by writing your own function that just puts the serial date and format into a datetime and then calls "month" on the datetime object (see the 'ConvertFrom' syntax on https://www.mathworks.com/help/matlab/ref/datetime.html). This will not have any requirements on the Financial Toolbox, because it will only leverage the datetime method (which is included in base MATLAB).