J. Michalicka
J. Michalicka

Reputation: 35

Carbon interprets P1M in ISO 8601 as 1 minute instead of 1 month

I am using Laravel 11 and trying to work with ISO 8601 intervals using Carbon. However, I encountered an issue where Carbon interprets P1M as 1 minute (60 seconds) instead of 1 month. This is causing problems with my time calculations.

$interval = CarbonInterval::fromString('P1M');
echo $interval->totalSeconds; // Outputs: 60 (expected: seconds for 1 month)

As a temporary workaround, I’m using P30D to represent approximately one month.

Is there a way to make Carbon correctly interpret P1M as 1 month? Or is there a better approach to handle this in Laravel 11?

Any advice or guidance would be appreciated!

Upvotes: 0

Views: 140

Answers (1)

KyleK
KyleK

Reputation: 5121

fromString is from "human" string.

If you want ISO string use the normal construct:

$interval = new CarbonInterval('P1M');
echo $interval->totalSeconds;

Format for fromString from the doc:

CarbonInterval::fromString string $intervalDefinition returns CarbonInterval Creates a CarbonInterval from string.

Format:

Suffix Unit Example DateInterval expression
y years 1y P1Y
mo months 3mo P3M
w weeks 2w P2W
d days 28d P28D
h hours 4h PT4H
m minutes 12m PT12M
s seconds 59s PT59S

e. g. 1w 3d 4h 32m 23s is converted to 10 days 4 hours 32 minutes and 23 seconds.

Upvotes: 5

Related Questions