To work with dates in PHP I recommend you use the class DateTime
.
To create the current date is as easy as this:
$fechaActual=new DateTime();
You would be creating a real object that you can then configure to your liking using its huge amount of methods and related classes.
You can also present it on the screen with a certain format.
You can also check in what TimeZone
the system is creating the object and change the zone. It is very useful when for example you do not want to alter the TimeZone
of the system, but of that particular object.
Let's see an example where we create an object DateTime
. We will use var_dump
to see its structure and we will see an example of printing a date / time with a certain format:
$fechaActual=new DateTime();
/*Sólo para ver el objeto*/
var_dump($fechaActual);
/*Un ejemplo de salida de fecha con formato*/
echo "Fecha/Hora: ".$fechaActual->format('Y-m-d H:i:sP') . PHP_EOL;
Exit:
-------var_dump------------------------------
object(DateTime)#1 (3) {
["date"]=>
string(26) "2018-11-05 03:08:52.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(13) "Europe/Berlin"
}
-------fecha formateada---------------------
Fecha/Hora: 2018-11-05 03:08:52+01:00
Now we change the TimeZone
using the setTimezone
method:
$fechaActual->setTimeZone(new DateTimeZone('America/Caracas'));
var_dump($fechaActual);
echo "Fecha/Hora: ".$fechaActual->format('Y-m-d H:i:sP') . PHP_EOL;
Exit:
-------var_dump------------------------------
object(DateTime)#1 (3) {
["date"]=>
string(26) "2018-11-04 22:08:52.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(15) "America/Caracas"
}
-------fecha formateada---------------------
Fecha/Hora: 2018-11-04 22:08:52-04:00