// 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.