MATLAB: Rounding Time to next half hour

cieling time half hour

I have time stamps at one second increments (9/8/2015 14:31:01, 9/8/2015 14:31:02, 9/8/2015 14:31:03…) that I would like to round up to the next half hour. So 9/8/2015 14:31:01 would be 9/8/2015 15:00:00 9/8/2015 14:29:01 would be 9/8/2015 14:30:00 and so on. Is there something similar to Excel's ceiling function where I can specify to what fraction I want to round up to?

Best Answer

This is probably more efficient than it looks:
tv = ['9/8/2015 14:28:01'; '9/8/2015 14:29:01'; '9/8/2015 14:31:01'; '9/8/2015 14:31:02'; '9/8/2015 14:31:03'];
tv_dv = datevec(datenum(tv, 'mm/dd/yyyy HH:MM:SS')); % Generate ‘datevec’ Date Vectors
tv_rnd = datevec(datenum([tv_dv(:,1:4) [30*(tv_dv(:,5)<30) + 60*(tv_dv(:,5)>=30)] tv_dv(:,6)])); % Rounded Date Vectors
It uses the logic of the vector ‘[30*(tv_dv(:,5)<30) + 60*(tv_dv(:,5)>=30)]’ to brute-force round all minute values less than 30 to 30, and everything greater than 30 to 60. I let the logic of the datenum function take care of conversion, and then converted them back into date vectors (so I could check the result).
Remove the datevec call in tv_rnd to keep them as date numbers, or convert them back to date strings instead in your code.