How to validate that one datetime is greater than another
Show older comments
My class takes two datetimes startTime and endTime as input arguments. I would like to use argument validation to force endTime to be later than startTime, but mustBeGreaterThan does not accept datetimes.
Accepted Answer
More Answers (2)
Joshua Levin Kurniawan
on 17 May 2024
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
on 17 May 2024
Edited: Fangjun Jiang
on 17 May 2024
It seems fine in R2022b, R2023b and R2024a
a=now;
b=now;
mustBeGreaterThan(b,a)
mustBeGreaterThan(a,b)
2 Comments
Rich006
on 17 May 2024
Fangjun Jiang
on 17 May 2024
Edited: Fangjun Jiang
on 17 May 2024
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))
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!