Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL STR_TO_DATE() function returns null

I wanted to convert my date format From MMMM dd,yyyy to yyyy-MM-dd.

I tried using the following:

SET @dt_to = STR_TO_DATE(dateTo, '%d-%m-%Y');

but returns a NULL value.

How will I convert my date to yyyy-MM-dd format in MySQL?

EDITED:

I am creating a procedure in which the value of dateTo was received in the parameter. It is a date in MMMM dd, yyyy format. E.g. October 10, 2015.

NOTE:

The whole query does not return NULL when I use:

SET @dt_to = dateTo;
like image 624
ThEpRoGrAmMiNgNoOb Avatar asked Dec 06 '25 01:12

ThEpRoGrAmMiNgNoOb


2 Answers

To convert the date format first you need to use STR_TO_DATE to convert the input string to a date value

SET @dt_to = STR_TO_DATE(dateTo, '%M %d,%Y');

and then convert that date value to your required format

SET @dt_converted = DATE_FORMAT(dt_to, '%Y-%m-%d');

or all in 1 go

SET @dt_to = DATE_FORMAT(STR_TO_DATE(dateTo, '%M %d,%Y'), '%Y-%m-%d');
like image 65
PaulF Avatar answered Dec 08 '25 13:12

PaulF


If it's returning null then that means the extracted datetime value is illegal. You can try like below. See MySQL Documentation for more information.

SELECT STR_TO_DATE('October 10, 2015','%M %d,%Y');
like image 34
Rahul Avatar answered Dec 08 '25 15:12

Rahul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!