Calmonths issues with February

2 ビュー (過去 30 日間)
Björn
Björn 2016 年 2 月 13 日
コメント済み: Walter Roberson 2016 年 2 月 13 日
What is going wrong here?
Shifting to the month end works fine for this example:
t0 = datetime(2016,1,1);t1 = dateshift(t0,'end','month')+calmonths(1:3)
t1 =
29-Feb-2016 31-Mar-2016 30-Apr-2016
But we do not get the month end when starting in Feb 2016:
t0 = datetime(2016,2,2);t1 = dateshift(t0,'end','month')+calmonths(1:3)
t1 =
29-Mar-2016 29-Apr-2016 29-May-2016
I first thought that this is an issue of leap year but the same problem occurs for 2015.
But then again, it works for March:
t0 = datetime(2015,3,3);t1 = dateshift(t0,'end','month')+calmonths(1:3)
t1 =
30-Apr-2015 31-May-2015 30-Jun-2015
What's the issue?

回答 (2 件)

Walter Roberson
Walter Roberson 2016 年 2 月 13 日
January and March have 31 days, so "1 month" relative to them is more clearly "last day of February" or "last day of April". But February has 29 days in 2016, so "1 month" relative to February 29 could mean March 29 instead of March 31. I bet if you were to try starting from the last day of April (the 30th) that it would show one month later to be May 30th instead of May 31.
I do not know the solution except perhaps to use calendarDuration() more directly.
  1 件のコメント
Walter Roberson
Walter Roberson 2016 年 2 月 13 日
Yes, that makes sense.

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


Björn
Björn 2016 年 2 月 13 日
編集済み: Björn 2016 年 2 月 13 日
I found the answer: The term unit of a month is a bit ambigiuous. But going to the end of a month is not controversial... Therefore, shift teh date first to any day next month and then go to the end of the month:
t0 = datetime(2016,2,2);
t1 = dateshift(t0+calmonths(1:3),'end','month')
t1 =
31-Mar-2016 30-Apr-2016 31-May-2016

カテゴリ

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