Calculate the number of days between two datetimes?

86 ビュー (過去 30 日間)
Jussi Ikäheimo
Jussi Ikäheimo 2016 年 11 月 10 日
コメント済み: Peter Perkins 2016 年 11 月 18 日
How to calculate the number of days between two datetimes?
days(between(day1,day2)) does not work:
"Error using days (line xxx) Input data must be a real, numeric array."

採用された回答

Brendan Hamm
Brendan Hamm 2016 年 11 月 10 日
You can do:
days(day2-day1)
The issue is that the between function returns a calendarDuration and this is measured using variable time-frames like months and years which contain different numbers of days.

その他の回答 (1 件)

Peter Perkins
Peter Perkins 2016 年 11 月 15 日
between already calculated the difference between those two dates in days:
>> d1 = datetime('yesterday'); d2 = datetime('tomorrow');
>> between(d1,d2)
ans =
calendarDuration
2d
Even more explicitly:
> between(d1,d2,'days')
ans =
calendarDuration
2d
If you then want the number 2, use caldays:
>> caldays(between(d1,d2,'days'))
ans =
2
Hope this helps.
  2 件のコメント
Jussi Ikäheimo
Jussi Ikäheimo 2016 年 11 月 17 日
It seems that the 'days' option is needed in between(), otherwise an error results.
Peter Perkins
Peter Perkins 2016 年 11 月 18 日
Jussi, I'm not sure what you're saying. All I wanted to demonstrate was that between gives you back a quantity that already measures the number of days. If you need a numeric value, then caldays is the function you want to apply to that, not days.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeDates and Time についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by