Calmonths issues with February

2 vues (au cours des 30 derniers jours)
Björn
Björn le 13 Fév 2016
Commenté : Walter Roberson le 13 Fév 2016
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?

Réponses (2)

Walter Roberson
Walter Roberson le 13 Fév 2016
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 commentaire
Walter Roberson
Walter Roberson le 13 Fév 2016
Yes, that makes sense.

Connectez-vous pour commenter.


Björn
Björn le 13 Fév 2016
Modifié(e) : Björn le 13 Fév 2016
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

Catégories

En savoir plus sur Dates and Time dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by