SQL TODATETIMEOFFSET function
Returns a datetimeoffset. TODATETIMEOFFSET attaches an offset you supply; SWITCHOFFSET moves the same instant to a different offset.
- カテゴリ
- Dates & times
- Returns
datetimeoffset- In this category
- 35 of 121
構文
TODATETIMEOFFSET(GETDATE(), '-05:00')
SWITCHOFFSET(SYSDATETIMEOFFSET(), '+00:00')
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 | ts AT TIME ZONE 'zone' tags a timestamp; timestamptz has no stored offset |
| MySQL | Not built in | no offset type; CONVERT_TZ converts |
| SQLite | Not built in | no offset type |
| Oracle | Different name or syntax | SYSTIMESTAMP AT TIME ZONE or FROM_TZ |
例
SQL Server
SELECT TODATETIMEOFFSET('2024-01-15 09:30', '-05:00') AS tagged;
SQL Server
SELECT SWITCHOFFSET(SYSDATETIMEOFFSET(), '+00:00') AS utc_instant;
知っておくと便利なこと
- TODATETIMEOFFSET does not convert: it declares a zone-less value WAS in that offset, so tagging a UTC value with '-05:00' changes the instant.
- Fixed offsets freeze daylight saving: an offset captured in summer stays wrong in winter. AT TIME ZONE with a named zone handles DST.
- Both accept the offset as a '+hh:mm' string or as signed minutes: TODATETIMEOFFSET(d, -300) is the same as TODATETIMEOFFSET(d, '-05:00').
Questions about TODATETIMEOFFSET
TODATETIMEOFFSET or SWITCHOFFSET: which converts?
Neither converts zones the way AT TIME ZONE does. SWITCHOFFSET re-expresses one instant; TODATETIMEOFFSET just labels a zone-less value.
Why did my time shift by five hours?
You tagged a UTC value with -05:00 using TODATETIMEOFFSET. The function trusts the offset you gave; it never converts for you.
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, 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.