Given two datetime
s t1
, t2
, I want to calculate the duration between the two in weeks, and rounded up.
The build-in between
gives the number rounded down. For example,
>> t1=datetime('20220817','InputFormat','yyyyMMdd');
>> t2=datetime('20220812','InputFormat','yyyyMMdd');
>> char(between(t2,t1,'weeks')) % desire 1w
ans =
calendarDuration
0d
>> t2=datetime('20220804','InputFormat','yyyyMMdd');
>> char(between(t2,t1,'weeks')) % desire 2w
ans =
calendarDuration
1w
Of coruse, between
doesn't have to be used. calendarDuration
is inconvenient for me actually, as I want the number of weeks -- not the calendar duration. But I don't want to deal with the true number of days between t1
t2
based on the exact dates.
How do I get the number of weeks rounded up?
CodePudding user response:
You can extract the number of days using the function caldays, divide it by 7 and ceil the result:
t1=datetime('20220817','InputFormat','yyyyMMdd');
t2=datetime('20220812','InputFormat','yyyyMMdd');
ceil(caldays(between(t2,t1))/7)
ans =
1
t2=datetime('20220804','InputFormat','yyyyMMdd');
ceil(caldays(between(t2,t1))/7)
ans =
2