Rounding Time to next half hour

6 views (last 30 days)
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?

Accepted Answer

Star Strider
Star Strider on 9 Sep 2015
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.

More Answers (1)

Peter Perkins
Peter Perkins on 10 Sep 2015
In MATLAB R2014b or later:
>> d1 = datetime({'9/8/2015 14:31:01', '9/8/2015 14:31:02', '9/8/2015 14:31:03'})
d1 =
08-Sep-2015 14:31:01 08-Sep-2015 14:31:02 08-Sep-2015 14:31:03
>> d2 = dateshift(d1,'start','hour') + minutes(30)
d2 =
08-Sep-2015 14:30:00 08-Sep-2015 14:30:00 08-Sep-2015 14:30:00
  1 Comment
Trung Hieu Le
Trung Hieu Le on 17 Jun 2016
Hi Peter,
Could you help me revise the code to receive the rounding time to next half hour as my required output?
>> d1 = datetime({'9/8/2015 14:46:01'})
My required output:
08-Sep-2015 15:00:00
If I use your code:
>> d2 = dateshift(d1,'start','hour') + minutes(30)
The result will be 14:30:00.
If I revise the code:
d2 = dateshift(d1,'start','hour') + minutes(60)
I will receive the right answer, however, do you know which code will be automatically for this?
Thanks!

Sign in to comment.

Categories

Find more on Dates and Time in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!