I have a column date & from request date
there are some possibilities coming from the user
- date might come as empty
- date might come as a month and year & I have to make it a full date! like
20204/
=>2020-04-01
- date might come as normal date
2020-04-01
- date might come as
1/4/2020
I need to convert it to a real date like2020-04-01
I handle the first two but I do not know how to handle the third one or check if it is the full date!
my code:
$newDate = null; // 1
$ex = $request->expired_date;
if(DateTime::createFromFormat('Y-m-d', $myString) !== false){
$newDate = $ex; // 2
}else {
$removeSpace = str_replace(' ', '', $ex);
list($month, $year) = explode('/', $removeSpace);
$newDate = vsprintf('%s-%s-%s', [$year, $month, '1']); // 3
}
I just have 4 one left how can convert the date 1/4/2020
to 2020-04-01
?
CodePudding user response:
you can use strtotime function in php
$date="1/4/2020";
$new_date=date("Y-m-d",strtotime($date));
CodePudding user response:
You can use DateTime. First you pass the Date ('1/4/2020') to the DateTime constructor. Then you can use the DateTime function format. Give the function the wanted date format ('Y-m-d').
$dt = new DateTime('1/4/2020');
$fdt = $dt->format('Y-m-d');
// output: 2020-01-04
Note: But @NicoHaase is right. Why don't you validate the correct format already in the frontend?