Maddy
Maddy

Reputation: 2570

Convert date to closest end-of-month date MATLAB

I need to convert a datenumber to its closest end-of-month date. I found an online link but it is very inefficient for a large matrix (at http://www.mathworks.com/matlabcentral/fileexchange/26374-round-off-dates-and-times). Does Matlab (Financial Toolbox) has an inbuilt function for this? I couldn't find it.

date_in = 734421 ;
somefunction(date_in) --> Sept 2010

Thanks!

Upvotes: 4

Views: 2712

Answers (2)

gnovice
gnovice

Reputation: 125854

Basically, it sounds like you are asking for whether a given date is closer to the preceding or following month. You can greatly simplify the logic involved if you use the functions EOMDAY to find the date for the end of the month and ADDTODATE to shift the current month up or down by one. Here's an example function that takes a date number as input:

function closestString = closest_month(dateNumber)

  dateVector = datevec(dateNumber);
  daysInMonth = eomday(dateVector(1),dateVector(2));
  if dateVector(3) > daysInMonth/2
    dateNumber = addtodate(dateNumber,1,'month');
  else
    dateNumber = addtodate(dateNumber,-1,'month');
  end
  closestString = datestr(dateNumber,'mmm yyyy');

end

Upvotes: 6

abcd
abcd

Reputation: 42225

I had some errors in my previous version. Here's the logic incorporated into a function. It also checks for the month and updates accordingly.

function out = roundMonth(dateNumber)
    dateVector = datevec(dateNumber);
    day = dateVector(3);
    month = dateVector(2);
    year = dateVector(1);

    month = month + sign(day - 15 + double(~(month-2)))...
        + double(~(day-15 + double(~(month-2))));

    dateVector(1) = year + double((month-12)==1) - double((1-month)==1);
    dateVector(2) = mod(month,12) + 12*double(~mod(month,12));

    out = datestr(dateVector,'mmm yyyy');

EXAMPLES:

1.

roundMonth(datenum('10-Oct-2010'))

ans =

Sep 2010

2.

roundMonth(datenum('20-Oct-2010'))

ans =

Nov 2010

3.

roundMonth(datenum('20-Dec-2010'))

ans =

Jan 2011

4.

roundMonth(datenum('10-Jan-2010'))

ans =

Dec 2009

Upvotes: 1

Related Questions