MATLAB: Datetime comparison near full hours

arraycomparisondatetimehourMATLABmatrix

Hello,
I have this piece of code that compares two sets of datetimes:
c = 1
for k = 1:size(TR_SoftStart,1)
Years = abs(year(PC_SoftStart) - year(TR_SoftStart.Data(k))) < 1;
Months = abs(month(PC_SoftStart) - month(TR_SoftStart.Data(k))) < 1;
Days = abs(day(PC_SoftStart) - day(TR_SoftStart.Data(k))) < 1;
Hours = abs(hour(PC_SoftStart) - hour(TR_SoftStart.Data(k))) < 1;
Minutes = abs(minute(PC_SoftStart) - minute(TR_SoftStart.Data(k))) <= 1;
Test = Years & Months & Days & Hours & Minutes;
if any(Test,'all')
disp(k)
else
errors_SoftStart(c,:) = TR_SoftStart(k,:);
c = c + 1;
end
end
It basically checks if the datetimes on TR_SoftStart have pairs on PC_SoftStart with a ±1 minute tolerance. However, there is one case in which the script doesn't work. Whenever it's close to the full hour (e.g.: 15:59:00 and 16:00:00) it doesn't understand that it infact has just 1 minute between them. I know that it's because the math used analyses only the individual parameters (years, then months, and so on). I'm really struggling to come up with a workaround for this. Any ideas?
Thanks in advance,
Arthur.

Best Answer

Don't bother splitting the time components yourself.
t1 = datetime('9-mar-2020 16:00:00');
t0 = datetime('9-mar-2020 15:59:03');
dt = t1-t0
dt =
duration
00:00:57
Here are two datetimes which are 1 minute appart. Subtracting them returns a duration datatype.
Set your tolerance value as another duration object
tol = duration(0,1,0); % 1 minute duration
dt < tol; % true