Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert varchar to datetime format in mysql

Tags:

mysql

I am trying to convert varchar to date time This is what I have now, and it is not working for me. I always get the have value

STR_TO_DATE(REPLACE(LEFT('5/16/2011 20:14 PM', LOCATE('M' , '5/16/2011 20:14 PM')-3), '/',','),'%m-%d-%Y %T')

This following code returns 5,16,2011 20:14

select REPLACE(LEFT('5/16/2011 20:14 PM', LOCATE('M' , '5/16/2011 20:14 PM')-3), '/',',')

my current output is emply string now. it should be 2011-05-16 20:14:00

How can i get this to work?

thanks

like image 495
Jaylen Avatar asked Mar 13 '13 20:03

Jaylen


People also ask

How do you resolve the conversion of a varchar data type to a datetime data type resulted in an out of range value?

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value. You need separators for the date like a “/”, a “.” or a “-“. We use substring to concatenate the “-” to use an acceptable date format and then we use the CONVERT function to convert the characters to sql date.

What is the format of datetime in MySQL?

MySQL retrieves and displays DATETIME values in ' YYYY-MM-DD hh:mm:ss ' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59' . The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.

How do I convert a date to a string in MySQL?

In MySQL, DATE_FORMAT function converts a DATE or DATETIME value to string using the specified format. In Oracle, you can use TO_CHAR function. Note that the DATE_FORMAT and TO_CHAR use different format strings.


1 Answers

If your varchar is like this:

5/16/2011 20:14 PM

you can convert it to datetime using this:

SELECT STR_TO_DATE('5/16/2011 20:14 PM', '%c/%e/%Y %H:%i')

or this to format it like you want:

SELECT DATE_FORMAT(STR_TO_DATE('5/16/2011 20:14 PM', '%c/%e/%Y %H:%i'), '%Y-%m-%d %H:%m:%s')
like image 145
fthiella Avatar answered Oct 13 '22 00:10

fthiella