Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to reverse the output of EXTRACT() in MySQL

I have the following query –

SELECT NOW(6) AS output1, CONCAT(EXTRACT(YEAR_MONTH FROM NOW()), EXTRACT(DAY FROM NOW()), EXTRACT(HOUR_MICROSECOND FROM NOW(6))) AS output2;
+----------------------------+--------------------+
| output1                    | output2            |
+----------------------------+--------------------+
| 2021-12-07 02:06:28.783259 | 202112720628783259 |
+----------------------------+--------------------+

Now I want to reverse the result – 202112720628783259 to 2021-12-07 02:06:28.783259. But I can’t think of a way to do it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In the output2, the day, hour, and minute have one digit. So you can’t reliably parse that back to YYYY-MM-DD HH:MM:SS.

I suggest you instead use DATE_FORMAT() and its reverse, STR_TO_DATE().

SELECT NOW(6) AS output1, DATE_FORMAT(NOW(6), '%Y%m%d%H%i%s%f') as output2
+----------------------------+----------------------+
| output1                    | output2              |
+----------------------------+----------------------+
| 2021-12-06 20:44:31.927978 | 20211206204431927978 |
+----------------------------+----------------------+
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading