Convertir marca de tiempo a fecha en la consulta MySQL


Quiero convertir un timestamp en MySQL a una fecha.

Me gustaría formatear el usuario.campo de registro en el archivo de texto como yyyy-mm-dd.

Aquí está mi SQL:

$sql = requestSQL("SELECT user.email, 
                   info.name, 
                   FROM_UNIXTIME(user.registration),
                   info.news
                   FROM user, info 
                   WHERE user.id = info.id ", "export members");

También probé la conversión de fecha con:

DATE_FORMAT(user.registration, '%d/%m/%Y')
DATE(user.registration)

Echo el resultado antes de escribir el archivo de texto y obtengo:

Email1;name1;DATE_FORMAT(user.registro, "% d / % m/ % Y"); noticia1

Correo electrónico2; nombre2; noticias2

¿Cómo puedo convertir ese campo a la fecha?

Author: juergen d, 2012-02-12

9 answers

DATE_FORMAT(FROM_UNIXTIME(`user.registration`), '%e %b %Y') AS 'date_formatted'
 281
Author: Yatin,
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
2013-08-23 15:21:52

Convertir la marca de tiempo a la fecha en MYSQL

Haga la tabla con una marca de tiempo entera:

mysql> create table foo(id INT, mytimestamp INT(11));
Query OK, 0 rows affected (0.02 sec)

Insertar algunos valores

mysql> insert into foo values(1, 1381262848);
Query OK, 1 row affected (0.01 sec)

Echa un vistazo

mysql> select * from foo;
+------+-------------+
| id   | mytimestamp |
+------+-------------+
|    1 |  1381262848 |
+------+-------------+
1 row in set (0.00 sec)

Convierte el número a una marca de tiempo:

mysql> select id, from_unixtime(mytimestamp) from foo;
+------+----------------------------+
| id   | from_unixtime(mytimestamp) |
+------+----------------------------+
|    1 | 2013-10-08 16:07:28        |
+------+----------------------------+
1 row in set (0.00 sec)

Convertirlo en un formato legible:

mysql> select id, from_unixtime(mytimestamp, '%Y %D %M %h:%i:%s') from foo;
+------+-------------------------------------------------+
| id   | from_unixtime(mytimestamp, '%Y %D %M %h:%i:%s') |
+------+-------------------------------------------------+
|    1 | 2013 8th October 04:07:28                       |
+------+-------------------------------------------------+
1 row in set (0.00 sec)
 51
Author: Eric Leschinski,
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-02-18 00:06:55

Para obtener una fecha que usted puede cast it

cast(user.registration as date)

Y para obtener un uso de formato específicodate_format

date_format(registration, '%Y-%m-%d')

SQLFiddle demo

 44
Author: juergen d,
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-02-03 10:52:23

Si el campo registration es de hecho de tipo TIMESTAMP usted debería ser capaz de hacer:

$sql = "SELECT user.email, 
           info.name, 
           DATE(user.registration), 
           info.news
      FROM user, 
           info 
     WHERE user.id = info.id ";

Y el registro debe aparecer como aaaa-mm-dd

 18
Author: cs0lar,
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
2012-02-12 19:03:36

Simplemente use la función de FECHA de mysql:

mysql> select DATE(mytimestamp) from foo;
 9
Author: Morey,
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
2016-02-03 01:02:50

Debes convertir timestamp a date.

select FROM_UNIXTIME(user.registration, '%Y-%m-%d %H:%i:%s') AS 'date_formatted'

FROM_UNIXTIME

 4
Author: Jaydeep Mor,
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-28 05:54:57

Si está recibiendo la consulta en su salida, debe mostrarnos el código que en realidad se hace eco del resultado. ¿Puede publicar el código que llama a requeteSQL?

Por ejemplo, si ha utilizado comillas simples en php, imprimirá el nombre de la variable, no el valor

echo 'foo is $foo'; // foo is $foo

Esto suena exactamente como su problema y estoy seguro de que esta es la causa.

También, intente eliminar el símbolo @ para ver si eso ayuda al darle más información.

De modo que

$SQL_result = @mysql_query($SQL_requete); // run the query

Se convierte en

  $SQL_result = mysql_query($SQL_requete); // run the query

Esto detendrá cualquier supresión de errores si la consulta está lanzando un error.

 2
Author: Fraser,
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
2012-02-12 20:01:04

Lo hice con la función 'date' como se describe en aquí :

(SELECT count(*) as the-counts,(date(timestamp)) as the-timestamps FROM `user_data` WHERE 1 group BY the-timestamps)
 1
Author: Emanuel Graf,
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-04-24 12:03:36

Intenta:

SELECT strftime("%Y-%d-%m", col_name, 'unixepoch') AS col_name

Formateará la marca de tiempo en milisegundos a yyyy-mm-dd string.

 0
Author: Vitaliy A,
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
2016-02-04 14:13:48