How to insert date and datetime into a table in MySQL?
The big problem is that after insert
, all the values that have date, are as zeros and in the format yyyy-dd-mm
and not dd/mm/yyyy
, as it was initially entered. How can I insert these values into the formatting I want?
2 answers
You cannot directly enter data in any format you want in MySQL for Fields datetime and timestamp. The format MySQL uses is the ISO standard: AAAA-MM-DD HH:MM:SS
and some variants in the same order.
However, this does not prevent the user from converting the formats at the time of input and output of the data-remembering that in any case, the storage format will remain the same in the DB.
See how to do this conversion using MySQL's own functions:
to display dates as dd/mm/aaaa
in SELECT
:
With the function DATE_FORMAT( data, formato )
you can convert a date into a formatted string.
Example for your table:
SELECT usr_idusuario, DATE_FORMAT( evn_dtevento, "%d/%m/%Y" ) AS data_evento FROM evn_evento;
How to use a string dd/mm/aaaa
when doing INSERT
:
The function that does the inverse of the above example is STR_TO_DATE( string, formato )
.
Applying to your table:
INSERT INTO usr_idusuario SET evn_dtevento = STR_TO_DATE( "31/05/2014", "%m/%d/%Y" ), ...
How to use a string dd/mm/aaaa
in the clause WHERE
:
SELECT campos FROM tabela WHERE dia = STR_TO_DATE( "31/05/2014", "%m/%d/%Y" );
Or for a range:
SELECT campos FROM tabela
WHERE dia BETWEEN
STR_TO_DATE( "01/05/2014", "%m/%d/%Y" ) AND
STR_TO_DATE( "31/10/2014", "%m/%d/%Y" ) ;
Placeholders of the most common formats for our locale :
%d Dia (00..31)
%e Dia (0..31)
%m Mês (00..12)
%y Ano (dois dígitos)
%Y Ano (quatro dígitos)
%% Caractere %
%H Horas (00..23)
%i Minutos (00..59)
%s Segundos (00..59)
%T Hora completa ( 24 horas, formato hh:mm:ss)
The formats are listed in full in the MySQL manual (en)
The default format is YYYY-MM-DD
, to extract the information must be treated in the application or in the query.
Creating the default value field in the bank, or passing now()
into INSERT
.
Will thus be completed with the current value.