Time arithmetic (no dates)
显示 更早的评论
I want to subtract two times only (no dates):
e.g. 4:30 - 2:45
Is there a function to do that? I do not want any dates involved.
3 个评论
James Tursa
2022-1-13
How are your times currently stored? As character strings, or ... ?
N
2022-1-13
James Tursa
2022-1-13
Well, the method for subtracting them does depend on how they are stored. E.g., you could store them as decimal seconds in double variables and just subtract them.
采纳的回答
更多回答(2 个)
datetime(0,0,0,4,30,0) - datetime(0,0,0,2,45,0)
1 个评论
John D'Errico
2022-1-13
LOL. That is really a better answer than mine. But it does use dates, so I tried to avoid using time functionality in MATLAB. Even so, +1.
4:30 is not a number. In order for you to work with something like that, you need to first convert it to a vector of TWO numbers. Thus something like [4,30], representing hours and minutes. In order to subtract them, do this:
timediff = [4 30] - [2 45]
The problem is, now you need to work in base 60. That is, if the second element in that time vector is greater than 60, or less than 0, you need to resolve the issue with a carry. Something like...
while timediff(2) < 0
timediff = timediff + [-1 60];
end
while timediff(2) > 60
timediff = timediff + [1 -60];
end
timediff
You can make a simple function of this. If the first element exceeds 24, or is less than zero, you will need to think about how this would work for time differentials that are more than days, or even weeks, etc. The same idea would apply then. Just remember there are 24 hours in a day.
类别
在 帮助中心 和 File Exchange 中查找有关 Calendar 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!