一般ISV在面對本地客戶時對時間相關的處理,通常都時區信息都是不敏感的。可是如今雲的世界裏爲了讓你們把時間處理的方式統一塊兒來,雲上的服務都是以UTC時間爲準的,如今若是做爲一個ISV來講就算你面對的客戶只是本地用戶可是你打算利用雲來爲你進行的應用提供更多的功能和便捷性時,你就須要採用UTC時間來處理跟相關的代碼了。html
在SQL Server數據庫處理時間相關的數據時,咱們經常會使用DateTime類型或者DateTime2類型來處理數據,其實早在SQL Server 2008發佈時,數據庫就開始支持DatetimeOffset數據類型了,DatetimeOffset天生出來就是爲了處理時區問題的sql
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
咱們會發現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
小結:htm
採用DatetimeOffset來存儲時間,經過DatetimeOffset來處理時間可讓你的代碼更加穩健,更加國際範blog
相關文章:《Azure 上SQL Database(PaaS)Time Zone時區問題處理》get