// dates & times reference

SQL date format codes reference

Every engine has its own mask language for the same idea; this maps the common patterns between TO_CHAR, DATE_FORMAT, STRFTIME and FORMAT.

類別
Dates & times
Returns
text
In this category
100 of 121

語法

TO_CHAR(d, 'YYYY-MM-DD')
DATE_FORMAT(d, '%Y-%m-%d')

Each block is a separate form. The support table and the examples show which engine takes which.

引擎支援

引擎Support備註
SQL Server 是 FORMAT 'yyyy-MM-dd' / CONVERT styles
PostgreSQL 是 to_char 'YYYY-MM-DD'
MySQL 是 DATE_FORMAT '%Y-%m-%d'
SQLite 是 strftime '%Y-%m-%d'
Oracle 是 TO_CHAR 'YYYY-MM-DD'

範例

PostgreSQL

SELECT to_char(now(), 'YYYY-MM-DD HH24:MI:SS');

MySQL

SELECT DATE_FORMAT(NOW(), '%Y-%m-%d %H:%i:%s');

SQLite

SELECT strftime('%Y-%m-%d %H:%M:%S', 'now');

小知識

  • Year-month-day: PostgreSQL/Oracle 'YYYY-MM-DD', MySQL/SQLite '%Y-%m-%d', SQL Server FORMAT 'yyyy-MM-dd' or CONVERT style 120/112.
  • Weekday and month names: to_char 'fmDay, DD fmMonth', DATE_FORMAT '%W %d %M', FORMAT 'dddd, dd MMMM'; each follows the session or culture language. SQLite has no name codes.
  • Minutes are the classic trap: MySQL uses %i (its %M is the month name), SQLite uses %M, PostgreSQL and Oracle use MI (MM is the month), and SQL Server FORMAT uses mm (MM is the month).

Questions about Format codes

Why do the mask codes differ so much?

Each vendor borrowed a different tradition: Oracle's TO_CHAR masks (PostgreSQL copied them), C's strftime percent codes (MySQL and SQLite), and .NET custom format strings (SQL Server FORMAT).

Is there a mask that works everywhere?

No. Even ISO 'YYYY-MM-DD' needs three spellings. Build a thin formatting helper per engine and keep the business code mask-free.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.