Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql STR_TO_DATE not working

I have a table with a varchar column called birthday

CREATE TABLE IF NOT EXISTS `test` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `birthday` varchar(30) COLLATE utf16_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf16 COLLATE=utf16_unicode_ci AUTO_INCREMENT=5 ;

INSERT INTO `test` (`id`, `birthday`) 
VALUES (1, '20041225'),
       (2, '2004-12-25'),
       (3, '19941225'),
       (4, '19941201');

I try to run this query:

SELECT str_to_date(birthday,"%Y%m%d") 
FROM `test` 
WHERE 1

But it always return rows with null values.

If I run the query:

SELECT str_to_date('20141225',"%Y%m%d") 
FROM `test` 
WHERE 1

It will return 2014-12-25

So what wrong with my query?

like image 765
Thinh Phan Avatar asked Jan 09 '23 22:01

Thinh Phan


2 Answers

Leave it to simpler functions. DATE() returns the date part of a string in YYYY-MM-DD format:

SELECT DATE(birthday) FROM `test`

Result:

2004-12-25      
2004-12-25      
1994-12-25      
1994-12-01      

The reason your code isn't working is that STR_TO_DATE() expects the same input and output formats, e.g. STR_TO_DATE('2014-08-29', '%Y-%m-%d'). Take a look at the examples in the documentation. This function is used mostly to convert dates or times from one format to another, where the original format is something from outside MySQL and you want to import the data into MySQL's date format for example - in this case, you'll know what the original date format is.

Example:

SELECT STR_TO_DATE('20041225', '%Y-%m-$d');   -- null - formats don't match
SELECT STR_TO_DATE('2004-12-25', '%Y-%m-%d'); -- 2004-12-25 - formats match
like image 73
scrowler Avatar answered Jan 19 '23 19:01

scrowler


You have COLLATE problem with your creation of table. If you use utf8_unicode_ci then there is no any problem. See this example on sqlfiddle. More about collation you can read this Post.

like image 34
Sadikhasan Avatar answered Jan 19 '23 21:01

Sadikhasan