Función NOW () en PHP


¿Hay una función PHP que devuelve la fecha y hora en el mismo formato que la función MySQL NOW()?

Sé cómo hacerlo usando date(), pero estoy preguntando si hay una función sólo para esto.

Por ejemplo, para devolver:

2009-12-01 00:00:00
Author: vaxquis, 2010-01-03

14 answers

No además:

date("Y-m-d H:i:s")
 851
Author: troelskn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-10 14:23:17
date('Y-m-d H:i:s')

Mira aquí para más detalles: http://pl.php.net/manual/en/function.date.php

 124
Author: hsz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-10 14:23:52

Con la versión de PHP >= 5.4 DateTime puede hacer esto: -

echo (new \DateTime())->format('Y-m-d H:i:s');

Ver que funciona .

 90
Author: vascowhite,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-29 10:00:25

Utilice esta función:

function getDatetimeNow() {
    $tz_object = new DateTimeZone('Brazil/East');
    //date_default_timezone_set('Brazil/East');

    $datetime = new DateTime();
    $datetime->setTimezone($tz_object);
    return $datetime->format('Y\-m\-d\ h:i:s');
}
 29
Author: user1786647,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-20 18:15:38

Prueba esto:

date("Y-m-d H:i:s");
 23
Author: streetparade,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-10 14:23:43

MySQL function NOW() devuelve la marca de tiempo actual. La única manera que encontré para PHP es usando el siguiente código.

$curr_timestamp = date('Y-m-d H:i:s');
 14
Author: Shriganesh Shintre,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-08 03:57:08

Mimetismo en PHP

Para imitar la función MySQL NOW() en PHP se puede usar date_create()->format('Y-m-d H:i:s'). Este enfoque le permite manejar manipulaciones de tiempo / zona horaria más fácilmente que date('Y-m-d H:i:s'). Es más legible y funciona desde php 5.2.

$now = date_create('now')->format('Y-m-d H:i:s'); // works in php 5.2 and higher  
$now = date_create()->format('Y-m-d H:i:s'); // also works in php 5.2
$now = new DateTime('now')->format('Y-m-d H:i:s'); // syntax error!!!
$now = (new DateTime('now'))->format('Y-m-d H:i:s'); // works in php 5.4 and higher   
$now = date('Y-m-d H:i:s'); // works as well, but it's less nice then date_create()

La razón por la que esto funciona es porque la función MySQL NOW() da el valor DateTime en este formato: 'YYYY-MM-DD HH:MM:SS'. Ver aquí: https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_now. Un hecho interesante es que es posible obtener el formato datetime ejecutando esta consulta: SHOW VARIABLES LIKE 'd%e_format', el resultado podría ser algo como esto:

Variable_name     Value     
date_format       %Y-%m-%d
datetime_format   %Y-%m-%d %H:%i:%

Las variables aquí arriba son variables de solo lectura. Así que no puedes cambiarlo. Supongo que la función MySQL NOW() obtiene su formato de la variable datetime_format.

Date_create () - > format () VS date()

Los hechos favorables de date_create('now')->format('Y-m-d H:i:s') sobre date('Y-m-d H:i:s') son:

  • manipulaciones de tiempo más fáciles de manejar
  • más fácil de manejar zonas horarias
  • más o. o. p.

Más fácil de manejar manipulaciones de tiempo

date_create() acepta un formato de fecha/hora relativo (como now, yesterday o +1 day) ver este enlace , ejemplo:

$tomorrow = date_create('+1 day')->format('Y-m-d H:i:s'); 

date() también acepta un formato de fecha/hora relativo, como este:

$tomorrow = date('Y-m-d H:i:s', strtotime('+1 day'));
$tomorrow = date('Y-m-d H:i:s', (time() + 86400)); // 86400 seconds = 1 day

Zonas horarias más fáciles de manejar

Cuando las zonas horarias importan, el uso de date_create()->format() tiene mucho más sentido que date() porque date() utiliza el valor predeterminado zona horaria configurada en php.ini en la directiva date.timezone. (enlace: http://php.net/manual/en/datetime.configuration.php#ini.date.timezone). Es posible cambiar la zona horaria por ejemplo, date_default_timezone_set('Asia/Tokyo');. Pero la desventaja de eso es que afectará a todas las funciones de fecha / hora. Este problema no existe si está utilizando date_create()->format() en combinación con timezone_open().

Vea una lista de todas las zonas horarias soportadas: http://php.net/manual/en/timezones.php . Lo gracioso es que incluso apoya el círculo polar Ártico y la Antártida.

Más o. o. p.

O. O. P. usa el Objeto state-full. Así que prefiero pensar de esta manera:

Create a DateTime Object. Use the DateTime that applies for tomorrow. Give me the datetime in format 'Y-m-d H:i:s'

Entonces pensar de esta manera: {[35]]}

Give me a date time string in format 'Y-m-d H:i:s', use strtotime() to calculate the Unix timestamp that applies for tomorrow.

Por lo tanto, diría que el enfoque date_create()->format() es más legible para mí que date().

Ejemplo de date_create () - >format()

Utilizo este enfoque para mis proyectos si tengo que rellenar un array. Como esto:

$array = array(
    'name' => 'John',
    'date_time' => date_create('now')->format('Y-m-d H:i:s'), // uses the default timezone
    'date_time_japan' => date_create('now', timezone_open('Asia/Tokyo'))->format('Y-m-d H:i:s'),
);
 14
Author: Julian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-19 09:02:24

Estaba buscando la misma respuesta, y se me ocurrió esta solución para PHP 5.3 o posterior:

$dtz = new DateTimeZone("Europe/Madrid"); //Your timezone
$now = new DateTime(date("Y-m-d"), $dtz);
echo $now->format("Y-m-d H:i:s");
 13
Author: santi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-09 16:41:35

Uso strftime:

strftime("%F %T");
  • %F es lo mismo que %Y-%m-%d.

  • %T es lo mismo que %H:%M:%S.

Aquí está una demo en ideone.

 13
Author: Danny Beckett,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-06 14:39:41

Una respuesta más que encuentro fácil de usar:

echo date('c'); 

// 2015-07-27T00:00:00+02:00

Esto es Fecha ISO 8601 (añadida en PHP 5) que MySQL utiliza

Editar

MySQL 5.7 no permite zona horaria en la fecha y hora por defecto. Puede desactivar el error con SQL_MODE=ALLOW_INVALID_DATES, vea la respuesta aquí para más detalles: https://stackoverflow.com/a/35944059/2103434 Pero eso también significa que la zona horaria se perderá al guardar en la base de datos!

Por defecto MySQL utiliza la zona horaria del sistema, y mientras php use la misma zona horaria, debería estar bien. En mi caso CET / UTC + 2.

Eso significa que si inserto 2015-07-27T00:00:00+02:00 en la base de datos, solo se almacenará 2015-07-27T00:00:00 (¡pero esa es la hora local correcta!).

Cuando vuelvo a cargar el tiempo en php,

$importedDate = new \DateTime('2015-07-27T00:00:00')

Asumirá automáticamente que es la zona horaria +02:00 ya que es la predeterminada. Imprimir esto será correcto de nuevo:

echo $importedDate->format('c');
// 2015-07-27T00:00:00+02:00

Para estar seguro, utilice siempre UTC en el servidor, especifíquelo en MySQL y PHP, y luego, solo conviértalo a su configuración regional de usuarios cuando muestre la fecha:

date_default_timezone_set('UTC');
$importedDate = new \DateTime('2015-07-27T00:00:00+02:00');
echo $importedDate->format('c');
// 2015-07-27T00:00:00+02:00
$importedDate->setTimezone(new \DateTimeZone("America/New_York"));
echo $importedDate->format('c');
// 2015-07-26T18:00:00-04:00
 12
Author: Richard87,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-22 08:41:38

O puede utilizar DateTime constantes :

echo date(DateTime::W3C); // 2005-08-15T15:52:01+00:00

Aquí está la lista de ellos:

ATOM = "Y-m-d\TH:i:sP" ;               // -> 2005-08-15T15:52:01+00:00
COOKIE = "l, d-M-Y H:i:s T" ;          // -> Monday, 15-Aug-2005 15:52:01 UTC
ISO8601 = "Y-m-d\TH:i:sO" ;            // -> 2005-08-15T15:52:01+0000
RFC822 = "D, d M y H:i:s O" ;          // -> Mon, 15 Aug 05 15:52:01 +0000
RFC850 = "l, d-M-y H:i:s T" ;          // -> Monday, 15-Aug-05 15:52:01 UTC
RFC1036 = "D, d M y H:i:s O" ;         // -> Mon, 15 Aug 05 15:52:01 +0000
RFC1123 = "D, d M Y H:i:s O" ;         // -> Mon, 15 Aug 2005 15:52:01 +0000
RFC2822 = "D, d M Y H:i:s O" ;         // -> Mon, 15 Aug 2005 15:52:01 +0000
RFC3339 = "Y-m-d\TH:i:sP" ;            // -> 2005-08-15T15:52:01+00:00 ( == ATOM)
RFC3339_EXTENDED = "Y-m-d\TH:i:s.vP" ; // -> 2005-08-15T15:52:01.000+00:00
RSS = "D, d M Y H:i:s O" ;             // -> Mon, 15 Aug 2005 15:52:01 +0000
W3C = "Y-m-d\TH:i:sP" ;                // -> 2005-08-15T15:52:01+00:00

Para depurar prefiero una más corta sin embargo ( 3v4l.org):

echo date('ymd\THisP'); // 180614T120708+02:00
 7
Author: CPHPython,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-14 10:03:00

Me gusta la solución publicada por user1786647, la he actualizado un poco para cambiar la zona horaria a un argumento de función y agregar soporte opcional para pasar una cadena de tiempo Unix o datetime para usar para la marca de datos devuelta.

También incluye un respaldo para "setTimestamp"para los usuarios que ejecutan una versión inferior a PHP 5.3:

function DateStamp($strDateTime = null, $strTimeZone = "Europe/London") {
    $objTimeZone = new DateTimeZone($strTimeZone);

    $objDateTime = new DateTime();
    $objDateTime->setTimezone($objTimeZone);

    if (!empty($strDateTime)) {
        $fltUnixTime = (is_string($strDateTime)) ? strtotime($strDateTime) : $strDateTime;

        if (method_exists($objDateTime, "setTimestamp")) {
            $objDateTime->setTimestamp($fltUnixTime);
        } 
        else {
            $arrDate = getdate($fltUnixTime);
            $objDateTime->setDate($arrDate['year'], $arrDate['mon'], $arrDate['mday']);
            $objDateTime->setTime($arrDate['hours'], $arrDate['minutes'], $arrDate['seconds']);
        }
    }
    return $objDateTime->format("Y-m-d H:i:s");
}
 4
Author: Seth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-09 16:39:16

Puede usar la función de fecha de php con el formato correcto como parámetro,

echo date("Y-m-d H:i:s");
 4
Author: Som,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-08 18:53:28

Puedes usar la clase simplePHP para hacer esto:

echo $date->now();

Esta clase también proporciona muchos métodos útiles para la suma, resta y comparación de fechas. Puede consultar la página de tutoriales para obtener más ejemplos.

 -2
Author: isa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-11 08:42:50