SQL CONVERT date style
Returns a date formatted or parsed per a style number: 112 for YYYYMMDD keys, 120 or 126 for timestamps, and no two-digit-year style in new code.
- Returns
varchar / date- In this category
- 34 of 121
语法
CONVERT(varchar, GETDATE(), 120)
CONVERT(date, '20240115', 112)
CONVERT(varchar, GETDATE(), 112)
Each block is a separate form. The support table and the examples show which engine takes which.
引擎支持
| 引擎 | Support | 备注 |
|---|---|---|
| SQL Server | 是 | Supported under this name. |
| PostgreSQL | Different name or syntax | TO_CHAR masks instead of numeric styles |
| MySQL | Different name or syntax | DATE_FORMAT masks |
| SQLite | Different name or syntax | strftime formats |
| Oracle | Different name or syntax | TO_CHAR / TO_DATE masks |
示例
SQL Server
SELECT CONVERT(varchar(10), GETDATE(), 112) AS date_key; -- 20240115
SQL Server
SELECT CONVERT(varchar(23), GETDATE(), 120) AS odbc_ts;
SQL Server
SELECT CONVERT(date, '15/01/2024', 103) AS parsed; -- British dd/mm/yyyy
值得了解
- Styles 1-7 and 10-12 are two-digit-year forms; add 100 for four digits. Style 1 is mm/dd/yy, style 101 is mm/dd/yyyy; one dropped digit shifts the century.
- Without a style (or with style 0), parsing follows the session DATEFORMAT and LANGUAGE settings, so the same CONVERT works locally and flips dates in production.
- CAST has no style argument and always follows DATEFORMAT; once input is dd/mm or mm/dd, use CONVERT with 103 or 101 so the order is fixed in the query.
Questions about CONVERT date styles
Which CONVERT style is safest for storage?
112 (YYYYMMDD) for date keys, 120 or 126 for timestamps. They are unambiguous regardless of server language settings.
What is style 126?
ISO-8601 with T separator: yyyy-mm-ddThh:mi:ss.mmm, the right pick for JSON and XML payloads.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
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.