SQL TODATETIMEOFFSET function
Attaches a new offset to a naive datetime (TODATETIMEOFFSET) or shifts an aware value's offset without moving the instant (SWITCHOFFSET).
- Categoria
- Dates & times
- Returns
datetimeoffset- In this category
- 111 of 121
Sintaxe
TODATETIMEOFFSET(dt, '+02:00')
SWITCHOFFSET(dto, '-05:00')
Each block is a separate form. The support table and the examples show which engine takes which.
Suporte a mecanismos
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Sim | both: the native pair |
| PostgreSQL | Different name or syntax | AT TIME ZONE does both jobs by direction |
| MySQL | Different name or syntax | CONVERT_TZ for the shift; no tagging |
| SQLite | Not built in | nenhum |
| Oracle | Different name or syntax | FROM_TZ to tag; AT TIME ZONE to render |
Exemplos
SQL Server
SELECT SWITCHOFFSET('2026-08-01 14:30:00 +02:00', '-05:00'); -- 07:30 -05:00
SQL Server
SELECT TODATETIMEOFFSET(order_date, '-07:00') FROM orders;
PostgreSQL
SELECT TIMESTAMP '2026-08-01 14:30' AT TIME ZONE 'America/Los_Angeles'; -- tag
Bom saber
- TODATETIMEOFFSET does not convert; it asserts: TODATETIMEOFFSET('2026-08-01 14:30', '-05:00') claims that wall time was in -05:00. Wrong claim, wrong instant, no error.
- SWITCHOFFSET never changes the instant: 14:30+02:00 becomes 07:30-05:00. For 'same wall time, different zone' you need TODATETIMEOFFSET on the naive part.
- Neither takes a zone name: SWITCHOFFSET(d, 'Pacific Standard Time') fails with error 9812. For DST-aware conversion use AT TIME ZONE 'Pacific Standard Time' (SQL Server 2016+).
Questions about TODATETIMEOFFSET / SWITCHOFFSET
TODATETIMEOFFSET or AT TIME ZONE?
They overlap: AT TIME ZONE on a naive datetime tags it with a named zone and picks the DST-correct offset. TODATETIMEOFFSET (SQL Server 2008) takes only a fixed offset string or a number of minutes.
Why did SWITCHOFFSET 'change' my time?
It changed the display, not the instant; the wall clock differs because the offset differs. Check the UTC read if values look wrong.
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, 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.