from Exact Datevec Second Data by Patrick Flick
This function bypasses the problem with rounded date values, caused by the floating point representa

resultDateVec=exactDatevecSecondData (datenumValues)
% ----------------------------------------------------------------------
% o Author: Peter Karcher, Patrick Flick (Yello Strom GmbH)
%
% o Description: This function bypasses the problem with rounded date values, caused by the floating point representation of the
%                datetime. 
%                If you do datevec(datenum([ 0 0 0 0 1 0 ])) in Matlab it returns [ 0 0 0 0 0 59.999999999999993 ],
%                which can be annoying when, for example, adding a datenum value for 1 minute to a datenum value for 12:23:00 resulting
%                in 12:23:59.999... Now even rounding doesn't help you as it returns 12:23:60 instead of 12:24:00.
%                If you use this function: exactDatevecSecondData(datenum([ 0 0 0 0 1 0 ])) it returns [ 0 0 0 0 1 0 ], making it the 
%                solution to the previous example as it returns 12:24:00.
%                NOTICE:    This function fails if you are working with higher precision then seconds (e.g. milliseconds)
%                
%            
% o Parameter:
%   - datenumValues     : an array of datenums to be processed
%
% o Output:
%   - resultDateVec     : returns a datevec ( [ YYYY MM DD hh mm ss ]) rounded to full seconds
%
% o Example:
%           % this example returns all full minutes between 14:00:00 and 15:00:00 for a given date
%           datetime = datenum( [ 2008 08 30 14 00 00 ]);
%           for i=1:60,
%               datetime = datetime + datenum([ 0 0 0 0 1 0 ]);
%               exactDatevecSecondData(datetime)
%           end
% ----------------------------------------------------------------------
 
function resultDateVec=exactDatevecSecondData (datenumValues)

% --- Begin: test for correct input data
if(size(datenumValues,2) ~= 1)
    resultDateVec = -1;
    return
end
% --- End: test for correct input data

% precision for rounding to full seconds
precision = [0 0 0 0 0 1];

% adding 1/4 of a second to the datenum value to eliminate rounding errors
kill_round_error = datenum(precision)/4;
increasedDatenumValues = datenumValues + kill_round_error;

% creating datevec of added values
increasedDateVecs = datevec(increasedDatenumValues);

% rounding the seconds in the datevec matrix
resultDateVec = [increasedDateVecs(:,1:5) round(increasedDateVecs(:,6))];



Contact us at files@mathworks.com