检索 SQL 服务器 (2005) 中记录的日期时间的时区

Retrieving the timezone of a recorded datetime in SQL Server (2005)

testdate 为带有日期时间列 d 的 table。我执行了这个 sql 请求几次,并在每次执行之间更改了 OS 时区。

INSERT INTO [testdate] ([d])
     VALUES (CAST(GETDATE() AS DATETIME))

我得到了这个结果:

     ________________________
    | d (datetime)           |
.---|------------------------|
| 1 | 2016-09-08 15:15:28.847|
| 2 | 2016-09-08 18:15:45.407|
| 3 | 2016-09-08 11:17:23.317|
°----------------------------°

第一场在 GMT+6 进行,第二场在 GMT+9 进行,最后一场在 GMT+1(夏令时)进行。我相信我会在当前时区获得所有这些行。

这些日期时间值是否存储为 "snapshot"?或者有没有办法获取每个值的时区?

时区未与日期值一起存储。你可以阅读这个 article: Solving the Datetime Mystery:

So how does SQL Server internally store the dates? It uses 8 bytes to store a datetime value—the first 4 for the date and the second 4 for the time. SQL Server can interpret both sets of 4 bytes as integers. For the date portion, the value SQL Server stores is the number of days before or after a base date of January 1, 1900. Because of this storage protocol, SQL Server assumed the date of January 1, 1900, when I didn't supply the date in my first example. SQL Server internally stored a value of 0. A negative number represents a date earlier than January 1, 1900.

SQL Server stores the second integer for the time as the number of clock ticks after midnight. A second contains 300 ticks, so a tick equals 3.3 milliseconds (ms). You can see the values for days and clock ticks by converting a datetime value to a binary(8) value and using the substring function to extract each set of 4 bytes. The code in Figure 3 then converts each set of 4 bytes into an integer.

您可以使用 datetime 数据类型并将日期存储在 UTC 时区中,然后您可以格式化日期,同时以您想要的格式从数据库中检索它。