How can I convert a Sql Server 2008 DateTimeOffset to a DateTime

后端 未结 6 1413
独厮守ぢ
独厮守ぢ 2020-11-27 05:15

I\'m hoping to convert a table which has a DATETIMEOFFSET field, down to a DATETIME field BUT recalculates the time by taking notice of the offset.

6条回答
  •  Happy的楠姐
    2020-11-27 06:09

    I know this is an old question but, if you want to convert DateTimeOffset to a DateTime, I think you need to take into account the timezone of the server you are converting on. If you just do a CONVERT(datetime, @MyDate, 1) you will simply lose the time zone, which likely results in an incorrect conversion.

    I think you first need to switch the offset of the DateTimeOffset value, then do the conversion.

    DECLARE @MyDate DATETIMEOFFSET = '2013-11-21 00:00:00.0000000 -00:00';
    SELECT CONVERT(DATETIME, SWITCHOFFSET(@MyDate, DATEPART(tz,SYSDATETIMEOFFSET())));
    

    The result of converting '2013-11-21 00:00:00.0000000 -00:00' to a DateTime on a server who's offset is -7:00 will be 2013-11-20 17:00:00.000. With the above logic it doesn't mater what the time zone of the server or the offset of the DateTime value, it will be converted to DateTime in the servers time zone.

    I believe you need to do this because a DateTime value includes an assumption that the value is in the time zone of the server.

提交回复
热议问题