rounded time value with intervals
9 次查看(过去 30 天)
显示 更早的评论
Im trying to convey the seconds since midnight into the format HH:MM PM (or AM). So far I have this:
secondsSinceMidnight = 26850.431
minuteInterval = 15
datestr(seconds(timestamp),'HH:MM PM')
The problem is that when it's an time like '7:27 AM', it needs to say '07:30 AM' ( i.e. have the zero in front and round up to closest 15 min interval).
How would I go about those two fixes?
0 个评论
采纳的回答
Voss
2022-2-20
Something like this might work for your purposes:
secondsSinceMidnight = 26850.431;
minuteInterval = 15;
% round *up* to next 15 minutes:
% timestamp = ceil(secondsSinceMidnight/60/minuteInterval)*minuteInterval*60;
% or round to *nearest* 15 minutes:
timestamp = round(secondsSinceMidnight/60/minuteInterval)*minuteInterval*60;
% make a character array via datestr():
str = datestr(seconds(timestamp),'HH:MM PM');
% datestr doesn't include leading 0 with AM/PM format (see documentation),
% so: manually put leading 0 in if necessary:
if str(1) == ' '
str(1) = '0';
end
disp(str);
0 个评论
更多回答(1 个)
Cris LaPierre
2022-2-20
编辑:Cris LaPierre
2022-2-21
I think in this case, it's easiest to round the seconds to the closest 15-minute increment. This uses 24-hr time, so no AM/PM is necessary.
minuteInterval = 15;
secondsSinceMidnight = 26850.431;
% calculate the closest 15-minute increment
seconds15min = round(secondsSinceMidnight/minuteInterval/60)*minuteInterval*60;
% Convert to a duratoin
t = seconds(seconds15min)
% format the time
t.Format = 'hh:mm'
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!