How to validate that one datetime is greater than another
조회 수: 15 (최근 30일)
이전 댓글 표시
채택된 답변
Stephen23
2024년 5월 17일
편집: Stephen23
2024년 5월 17일
Do NOT convert to low-precision serial date numbers! Avoid deprecated DATENUM !
Argument validation lets you define your own validation function, which makes your task easy (and you get to write exactly the informative error messages that you want to see displayed):
A = datetime(1994,1,1);
B = datetime(2024,1,1);
myfun(A,B)
myfun(B,A)
function myfun(startTime,endTime)
arguments
startTime (1,1) {idt}
endTime (1,1) {idt,ilt(startTime,endTime)}
end
disp('okay!')
end
function idt(x)
assert(isdatetime(x),'Input must be a DATETIME.')
end
function ilt(s,e)
assert(s<e,'End time must be after start time.')
end
댓글 수: 5
Stephen23
2024년 5월 17일
편집: Stephen23
2024년 5월 17일
Some changes:
- move the validation functions to local functions (rather than methods),
- do not use the same name for the method and the class,
- define the class object as a method input. This requirement is explained here:
After that (see attached file), it works as expected:
A = datetime(1994,1,1);
B = datetime(2024,1,1);
obj = myClass();
obj.myMethod(A,B)
obj.myMethod(B,A)
추가 답변 (2개)
Joshua Levin Kurniawan
2024년 5월 17일
You can use traditional logical operator for datatime. Operator "<", if true, means that the first datatime will occurs sooner than the next variable. In this case, just use the following code
if startTime < endTime
disp("The data is valid");
else
disp("The data is invalid");
end
For further information, you can check out the following page
Fangjun Jiang
2024년 5월 17일
편집: Fangjun Jiang
2024년 5월 17일
It seems fine in R2022b, R2023b and R2024a
a=now;
b=now;
mustBeGreaterThan(b,a)
mustBeGreaterThan(a,b)
댓글 수: 2
Fangjun Jiang
2024년 5월 17일
편집: Fangjun Jiang
2024년 5월 17일
okay, I thought now() returns a datetime object. It was not. You can convert it to datenum()
a=datetime('now');
b=datetime('now');
mustBeGreaterThan(datenum(b),datenum(a))
mustBeGreaterThan(datenum(a),datenum(b))
참고 항목
카테고리
Help Center 및 File Exchange에서 Dates and Time에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!