Ash
Ash

Reputation: 415

Laravel, How to separate the month and year from one input as in a credit card

How to separate the month and year from a single text that contains the year and month in the same sentence as in a credit card, I want to save it as month=12, year=2022 if the input was 12/22

the input as below

 <input placeholder="MM/YY" type="text" name="expiry">

in controller                                        

 $request->input('expiry');

Upvotes: 2

Views: 2004

Answers (5)

Asra Fud Duha
Asra Fud Duha

Reputation: 630

Use the PHP explode(separator,string,limit) function to get month and year separated.

Note that here the parameter limit is optional.

According to your main question, it should be like the following.

$expiry = explode("/", $request->expiry);
$month = $expiry[0];
$year = $expiry[1];

Upvotes: 0

William Dias
William Dias

Reputation: 21

On the input you can use a javascript mask with the format MM/YYYY and in the controller just explode('/',$request->input('expiry')); with month = $exploded[0] and year = $exploded[1]

Upvotes: 0

Himani
Himani

Reputation: 47

$checkMe = "12/19";
echo date('m',strtotime($checkMe));
echo "<br>";
echo date('y',strtotime($checkMe));

Upvotes: 0

CodyKL
CodyKL

Reputation: 1064

$date = explode('/', $request->input('expiry')); // 12/22
$month = date[0];
$dt = DateTime::createFromFormat('y', $date[1]);
// get the full year
$year = $dates->format('Y'); // output : 2022

But be aware, if you use the format character 'y' in createFromFormat()... PHP documentation says:

'y' > A two digit representation of a year (which is assumed to be in the range 1970-2069, inclusive)

Upvotes: 1

Ronak J Vanpariya
Ronak J Vanpariya

Reputation: 73

You can use the PHP method print_r(explode("/",$str)); Thanks.

Upvotes: 0

Related Questions