How to get the date in php

1

Good afternoon, it turns out that I have a date in php which works but when it is more than 6 pm it happens to the other day this the code.

$fech = date("Y-m-d");

for example today is 20 and I already get 21 in Bogota, I hope you can help me thanks.

    
asked by juan perez 21.01.2018 в 01:24
source

2 answers

3

The problem was that I did not have the time zone for Bogotá. To define the time zone you can use date_default_timezone_set , in my case:

date_default_timezone_set("America/Bogota");
    
answered by 21.01.2018 в 01:40
1

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
    
answered by 21.01.2018 в 03:20