Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
718 views
in Technique[技术] by (71.8m points)

how to convert varchar to datetime format in 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...