Damon Malkiewicz
Damon Malkiewicz

Reputation: 463

datetimeoffset vs datetime2 for UTC on SQL Server

Are there any benefits to storing a UTC timestamp in a datetimeoffset field vs datetime2? It seems they're essentially the same.

+------------------------------------+-----------------------------+
| datetimeoffset                     | datetime2                   |
|------------------------------------+-----------------------------|
| 2021-02-12 16:48:11.0677934 +00:00 | 2021-02-12 16:48:11.0677934 |
+------------------------------------+-----------------------------+

Upvotes: 11

Views: 9353

Answers (1)

Dan Guzman
Dan Guzman

Reputation: 46203

The datetimeoffset data type will allow comparison between different offsets of the same time. e.g.:

SELECT 'equal'
WHERE
    CAST('2021-02-12T15:48:11.0677934-01:00' AS datetimeoffset) = CAST('2021-02-12T16:48:11.0677934+00:00' AS datetimeoffset).

If you are storing only UTC values (where the offset is always zero), you can save storage space with datetime2. datetimeoffset requires 10 bytes of storage whereas datetime2 needs 8 bytes for precision 5 or greater, 7 bytes for precision 3-4, and 6 bytes for precision 2 or less.

Upvotes: 18

Related Questions