Another option would be to do it with a DateTime
object, indicating that you want a specific TimeZone
for that object.
Working with objects is much more flexible (for example in the case of needing to work with date objects from different zones). And it has the advantage that the object keeps another type of information that may be useful later. The calculations are also simplified, for example if you need to calculate differences between dates, etc.
The object would be created like this:
$fecha = new DateTime('now', new DateTimeZone('America/Bogota'));
And to print it:
echo $fecha->format('Y-m-d');
If you make a var_dump
of that date object, you'll see everything in it:
var_dump($fecha);
The result would be:
object(DateTime)#1 (3) {
["date"]=>
string(26) "2018-01-20 21:05:30.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(14) "America/Bogota"
}
Suppose that later you want to know the TimeZone
of that object:
echo $fecha->getTimezone()->getName();
Will print:
America/Bogota
As you can see, working with objects opens up a wide range of possibilities.
Let's see a test code with the above, and using other TimeZone
.
VIEW DEMO IN REXTESTER
❯ Code:
$fecha = new DateTime('now', new DateTimeZone('America/Bogota'));
printFechaZone($fecha);
$fecha = new DateTime('now', new DateTimeZone('Australia/Sydney'));
printFechaZone($fecha);
$fecha = new DateTime('now', new DateTimeZone('Europe/Madrid'));
printFechaZone($fecha);
$fecha = new DateTime('now', new DateTimeZone('Asia/Calcutta'));
printFechaZone($fecha);
$fecha = new DateTime('now', new DateTimeZone('Africa/Luanda'));
printFechaZone($fecha);
function printFechaZone($miFecha){
echo 'Zona: '.$miFecha->getTimezone()->getName() . PHP_EOL;
echo 'Fecha-Hora: '.$miFecha->format('Y-m-d H:i:s') . PHP_EOL . PHP_EOL;
}
❯ Result:
Zona: America/Bogota
Fecha-Hora: 2018-01-20 21:17:12
Zona: Australia/Sydney
Fecha-Hora: 2018-01-21 13:17:12
Zona: Europe/Madrid
Fecha-Hora: 2018-01-21 03:17:12
Zona: Asia/Calcutta
Fecha-Hora: 2018-01-21 07:47:12
Zona: Africa/Luanda
Fecha-Hora: 2018-01-21 03:17:12