I am trying to divide a date and time variable into 3 variables to be able to later insert it into the database since these fields are separated, for this I am using a code similar to this:
<?php
$fecha = '2019-01-09';
list($anio, $mes, $dia) = explode("-", $fecha);
echo "Fecha: $fecha <br>";
echo "Año: $anio <br />";
echo "Mes: $mes <br />";
echo "Dia: $dia <br />";
$tiempo = '4:36 PM';
list($hora, $minutos) = explode(':', $tiempo);
list($min, $meria) = explode (' ', $minutos);
echo "Hora: $hora <br>";
echo "Minutos: $minutos <br>";
echo "Min: $min <br>";
echo "Meria: $meria";
?>
With the $date variable I had no problem since the character to exclude was always the same, which is "-", but with the time I have : and a space, I managed to solve the problem by doing an explode for each character, but I was wondering if could do that only in an explode.
In order not to go around so much dizzying the data, the simplest thing would be to join the date and time and create an object from them
DateTime
. Then with the help offormat
you can get the part of that object you want in the way you want it. In PHP, when you work with a true objectDateTime
you can get a lot of parts of that object and in different representations ( you can see the list here ).For example:
Departure:
php's preg_split is what you need http://us1.php.net/preg_split
splits a string using a regular expression, in this case I used a very basic one for : and white space.
EDIT
As I see that you are a beginner, with your same example to assign to variables, it is done like this:
Try like this: