MySQL – How to Format a Date Field into Different Languages in One Command

date formatMySQL

The following will return the day in Italian:

SET lc_time_names = 'it_IT';
select date_format('2018/01/01','%W') as day_italian;

However I need to convert or format the date into multiple languages, so it would return me another column in English, Japanese, so on…

My problem is that I have to set the locale BEFORE running the select command.

Best Answer

With a Stored Function, you can get it all in a single SELECT.

DELIMITER //

CREATE FUNCTION WDay(_d DATE, _locale VARCHAR(5))
    RETURNS VARCHAR(22)
    DETERMINISTIC
    SQL SECURITY DEFINER
BEGIN
    SET @@lc_time_names = _locale;
    RETURN DATE_FORMAT(_d, '%W');
END;
//
DELIMITER ;

SELECT WDay(NOW(), 'it_IT') AS it,
       WDay(NOW(), 'es_ES') AS es,
       WDay(NOW(), 'en_US') AS us;

+----------+--------+----------+
| it       | es     | us       |
+----------+--------+----------+
| giovedì  | jueves | Thursday |
+----------+--------+----------+

Caveat: This has the side effect of changing @@lc_time_names.