Home > front end >  generate credit card with 6 month expire
generate credit card with 6 month expire

Time:08-10

I have laravel project part of my code adds months and year in a database for generated cards the expiration month should be 6 months after generating the card

I have this code

        "year" => now()->format("Y"),
        "month" => now()->addMonths(6)->format("m"),

the problem is for the current month august I get the year 2022 and month 02 because this code gets month aug=8 6 =14

how to fix this?

for example for the august 2022 sample, I should get 02/2023

CodePudding user response:

Not sure where the now() function comes from, but I would recommend you yo use the DateTime/DateTimeImmutable object in PHP. You could do something like this to add 6 months to the current time:

<?php

var_dump((new DateTime())->add(new DateInterval('P6M'))->format('m/y'));

// Output: string(5) "02/23"

Or use the DateTime constructor to set a different point in time

<?php

var_dump((new DateTime('@1654072523'))->add(new DateInterval('P6M'))->format('m/y'));

// Output: string(5) "12/22"

If you'd like the values separately you can do something like the following:

<?php

// Create an instance of DateTime
$date = new DateTime('@1654072523');

// Add an interval of 6 months to the date time object
$futureDate = $date->add(new DateInterval('P6M'));

var_dump($futureDate->format('m'));
var_dump($futureDate->format('y'));

// Output: string(2) "12"
//         string(2) "22"

Or for your example:

        "year" => now()->addMonths(6)->format("Y"),
        "month" => now()->addMonths(6)->format("m"),

You can use all kinds of formatting options and variations, a list is available at the PHP docs, https://www.php.net/manual/en/datetime.format.php.

I hope this helps! If not, please clarify your question

CodePudding user response:

The solution is pretty simple in this case :D

$date = now()->addMonths(6);

"year" => $date->format('Y'),
"month" => $date->format("m"),

If the month you are creating it is January 2022, the date will hold July and 2022.

If the month you are creating it is September 2022,the date will hold the March and 2023

  • Related