Convert date to nearest month end MATLAB

I need to convert the datenumber number to its nearest end-of-month date. I found an online link, but it is very inefficient for a large matrix ( http://www.mathworks.com/matlabcentral/fileexchange/26374-round-off-dates-and-times ). Does Matlab ( Financial Toolbox ) have a built-in function for this? I could not find him.

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

Thanks!

+4
source share
2 answers

I had some errors in my previous version. Here the logic is included in the function. It also checks 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 
+1
source

Basically, it looks like you are asking if this date is closer to the previous or next month. You can greatly simplify the logic if you use the EOMDAY functions to find 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 
+6
source

All Articles