In Oracle, TO_CHAR function converts a datetime value to string using the specified format. In MySQL, you can use DATE_FORMAT function.
Note that the TO_CHAR and DATE_FORMAT format strings are different.
Oracle:
-- Convert the current date and time to string (year-month-day) SELECT TO_CHAR(SYSDATE, 'YYYY-MM-DD') FROM dual; # 2013-02-27
MySQL:
-- Convert the current date and time to string (year-month-day) SELECT DATE_FORMAT(SYSDATE(), '%Y-%m-%d'); # 2013-02-27
When you convert Oracle TO_CHAR function to DATE_FORMAT function in MySQL, you have to map the format specifiers:
Note that the day of the week returned by Oracle depends on NLS_TERRITORY setting of the current session and the value's range is 1 to 7 while MySQL %w range is 0 to 6, and 0 always used for Sunday and 6 for Saturday.
Consider the following example for Sunday, October 6th, 2024:
Oracle:
ALTER SESSION SET NLS_TERRITORY = 'America'; -- Sunday is 1 SELECT TO_CHAR(DATE '2024-10-06', 'D') FROM dual; # 1 ALTER SESSION SET NLS_TERRITORY = 'Spain'; -- Sunday is 7 now (week starts on Monday) SELECT TO_CHAR(DATE '2024-10-06', 'D') FROM dual; # 7 ALTER SESSION SET NLS_TERRITORY = 'Korea'; -- Sunday is 1 again SELECT TO_CHAR(DATE '2024-10-06', 'D') FROM dual; # 1
MySQL offers various way to get the day of the week, and they all return different results:
MySQL:
-- For %w Sunday is always 0 (0 = Sunday, 1 = Monday, ... 6 = Saturday) SELECT DATE_FORMAT('2024-10-06', '%w'); # 0 -- For DAYOFWEEK Sunday is always 1 (1 = Sunday, 2 = Monday, …, 7 = Saturday) to follow ODBC standard SELECT DAYOFWEEK('2024-10-06'); # 1 -- For WEEKDAY Sunday is always 6 (0 = Monday, 1 = Tuesday, … 6 = Sunday) SELECT WEEKDAY('2024-10-06'); # 6
Typical conversion examples:
Oracle | MySQL | |
1 | TO_CHAR(SYSDATE, 'YYYY-MM-DD') | DATE_FORMAT(SYSDATE(), '%Y-%m-%d) |
2 | TO_CHAR(SYSDATE, 'YYYYMMDDHH24MISS') | DATE_FORMAT(SYSDATE(), '%Y%m%d%H%i%s') |
3 | TO_CHAR(SYSDATE, 'DD-MON-YYYY') | DATE_FORMAT(SYSDATE(), '%d-%b-%Y') |
4 | TO_CHAR(SYSDATE, 'RRRR-MM-DD') | DATE_FORMAT(SYSDATE(), '%Y-%m-%d') |
5 | TO_CHAR(SYSDATE, 'D') | DAYOFWEEK(SYSDATE()) |
For more information, see Oracle to MySQL Migration.