Problem with capturing the time with date ("ymd") PHP

1

I have that variable to take the current date

  

$ current_date = date ("ymd");

I have a problem I do not know the exact time but after 6pm to 8pm it takes the data as the current date + 1

some solution for it? if I do:

  

$ current_datenew = date ("ymd", strtotime ($ current_date "- 1 days"));

that would take 1 day to the date you take but the problem is if there is a better solution for the date or this problem is common in php?

    
asked by Rob Robs 05.11.2018 в 02:03
source

1 answer

1

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
    
answered by 05.11.2018 / 03:23
source