Search code examples
phplaravelstripe-paymentsphp-carbon

Leading zeros on Stripe Exp_Month


Using the Stripe API I'm trying to show the credit cards expiration date.

I use exp_month to grab the month & and it works fine.

{{ $stripeCustomer->sources->data[0]->exp_month }}

My issue is there is no leading zero when I grab the month.
Output looks like this: June = 6. I want June to = 06

I tried using Carbon like this:

{{ Carbon\Carbon::parse($stripeCustomer->sources->data[0]->exp_month)->format('m') }}

but the data[0] throws the error:

DateTime::__construct(): Failed to parse time string (2) at position 0 (2): Unexpected character

So if I remove the data[0]

{{ Carbon\Carbon::parse($stripeCustomer->sources->exp_month)->format('m') }}

I get the leading 0, but I get the output of 08.. which is the current month at the time of this question.


How can I make this work so I get the leading zero and correct month?


Solution

  • You can use

    sprintf("%'02d", $stripeCustomer->sources->data[0]->exp_month);
    

    Change the 2 if you need more zeros.