Time arithmetic (no dates)

조회 수: 2 (최근 30일)
N
N 2022년 1월 13일
댓글: Steven Lord 2022년 1월 14일
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
N
N 2022년 1월 13일
I haven't stored them yet. it doesn't matter. I can store them as anything.
James Tursa
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.

댓글을 달려면 로그인하십시오.

채택된 답변

Walter Roberson
Walter Roberson 2022년 1월 13일
tdiff = (hours(4)+minutes(30)) - (hours(2) + minutes(45))
tdiff = duration
1.75 hr
[h, m, s] = hms(tdiff)
h = 1
m = 45
s = 0
  댓글 수: 1
Steven Lord
Steven Lord 2022년 1월 14일
To make that first line look a little closer to the representation in the original question:
t1 = duration(4, 30, 00)
t1 = duration
04:30:00
t2 = duration(2, 45, 00)
t2 = duration
02:45:00
tdiff = t1-t2
tdiff = duration
01:45:00

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Voss
Voss 2022년 1월 13일
datetime(0,0,0,4,30,0) - datetime(0,0,0,2,45,0)
ans = duration
01:45:00
  댓글 수: 1
John D'Errico
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.

댓글을 달려면 로그인하십시오.


John D'Errico
John D'Errico 2022년 1월 13일
편집: John D'Errico 2022년 1월 13일
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]
timediff = 1×2
2 -15
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
timediff = 1×2
1 45
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.

카테고리

Help CenterFile Exchange에서 Calendar에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by