How do I convert strings like '1021970'
(January 2, 1970) or '12021970'
(December 2, 1970) with varying month lengths into MySQL dates?
Asked
Active
Viewed 17 times
0

Tyler
- 161
- 1
- 11
-
You read the manual for `STR_TO_DATE` – Salman A May 09 '23 at 19:23
-
AND lpad https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_lpad – P.Salmon May 10 '23 at 08:39
1 Answers
0
In a string where the month doesn't have a leading zero (i.e. sometimes it has one digit, sometimes it has two digits), the day always has a leading zero, and the year is always four digits:
SELECT
IF(
LENGTH(`your_date_column`) = 7,
STR_TO_DATE(INSERT(`your_date_column`, 1, 0, '0'), '%m%d%Y'),
STR_TO_DATE(`your_date_column`, '%m%d%Y')
);
To test:
-- January 2, 1970.
SELECT
IF(
LENGTH('1021970') = 7,
STR_TO_DATE(INSERT('1021970', 1, 0, '0'), '%m%d%Y'),
STR_TO_DATE('1021970', '%m%d%Y')
);
-- December 2, 1970.
SELECT
IF(
LENGTH('12021970') = 7,
STR_TO_DATE(INSERT('12021970', 1, 0, '0'), '%m%d%Y'),
STR_TO_DATE('12021970', '%m%d%Y')
);

Tyler
- 161
- 1
- 11