Azure 上SQL Database(PaaS)Time Zone时区问题处理(进阶篇)

一般ISV在面对本地客户时对时间相关的处理,通常都时区信息都是不敏感的。可是如今云的世界里为了让你们把时间处理的方式统一块儿来,云上的服务都是以UTC时间为准的,如今若是做为一个ISV来讲就算你面对的客户只是本地用户可是你打算利用云来为你进行的应用提供更多的功能和便捷性时,你就须要采用UTC时间来处理跟相关的代码了。html

在SQL Server数据库处理时间相关的数据时,咱们经常会使用DateTime类型或者DateTime2类型来处理数据,其实早在SQL Server 2008发布时,数据库就开始支持DatetimeOffset数据类型了,DatetimeOffset天生出来就是为了处理时区问题的sql

image

参考上一个Blog 《Azure 上SQL Database(PaaS)Time Zone时区问题处理》,咱们一样要来解决时区的问题,咱们建立appcount表时,咱们采用下面语句

CREATE TABLE [dbo].[appcount2]( 
    [Id] [int] IDENTITY(1,1) NOT NULL, 
    [createtime] [datetime] NULL, 
    [CreatetimeWithOffset] [Datetimeoffset] NULL,
    PRIMARY KEY CLUSTERED (Id) 
)

插入数据时使用数据库

INSERT INTO    appcount(createtime,createtimewithoffset) VALUES(GetDate(),sysdatetimeoffset() AT TIME ZONE 'China Standard Time')

插入完数据咱们将数据在查询出来app

image

image

咱们会发现DateTimeOffset在处理时区问题时无论带不带时区的迁移语句的出来的时间都是正确的,可是DateTime字段的出来的时间明显就会有时间偏移错误。spa

咱们用下面的C#从.NET程序里面将这些时间数据取出来会如何呢?code

using (IDbConnection conn = new System.Data.SqlClient.SqlConnection(strConn))

            {
                conn.Open();
                var command = conn.CreateCommand();
                command.CommandText = "Select  id,createtime,CreatetimeWithOffset from appcount";
                var reader = command.ExecuteReader();
                while (reader.Read())
                {
                    var id = reader["id"];
                    var date = reader["createtime"];
                    var date2 = reader["createtimeWithOffset"];
                    var localDate = ((DateTimeOffset)date2).LocalDateTime;
                    Console.WriteLine("id:{0},createtime:{1},DateTimeInOffSet:{2},localdate:{3}", id, date,date2, localDate);
                }
                reader.Close();
                conn.Close();
            }

 

这里是代码执行结果:orm

image

 

小结:htm

采用DatetimeOffset来存储时间,经过DatetimeOffset来处理时间可让你的代码更加稳健,更加国际范blog

 

相关文章:《Azure 上SQL Database(PaaS)Time Zone时区问题处理get

相关文章
相关标签/搜索