Bassem Lhm Bassem Lhm - 1 year ago 53
MySQL Question

MySQL: converting date formats inside of strings

I have a list of file paths and dates stored in a database:

path | date
C:\folder\file1 %Y-%m-%d.csv | 2016-09-14
C:\folder\file2_%M %d %Y.csv | 2016-09-13
C:\folder\file3 %y%m%d.csv | 2016-08-31

The dates in the file paths are according to the
format convention.
The dates will change everyday.
I need to write a SELECT query that will return:

C:\folder\file1 2016-09-14.csv
C:\folder\file2_Sep 14 2016.csv
C:\folder\file3 160831.csv

I don't want to end up writing a never-ending
query with all the possible scenarios:

REPLACE(... REPLACE(REPLACE(path,'%Y',YEAR(date)),'%d',DAY(date))...)

Is there a way to do this with a MySQL built-in function?

Answer Source

You want DATE_FORMAT() here. It should replace format strings it recognizes with their values and ignore everything else.

SELECT DATE_FORMAT(date, path) AS result;

NOTE: %M Will give the full month ("September"), for the abbreviated month ("Sept") use %b.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download