Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
675 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...