How can I convert a Sql Server 2008 DateTimeOffset to a DateTime
To convert DateTimeOffset to DateTime, use the CONVERT function with style 1 for UTC format:
This code sample provides a DateTime in UTC from a DateTimeOffset, accounting for the offset.
Handling conversion
When dealing with conversions from DateTimeOffset to DateTime, consider nuances for maintaining the true chronological point.
Adjusting for timezone offsets
Mind the offset with DateTimeOffset. It's paramount that the DateTime reflects the original DateTimeOffset in UTC:
SWITCHOFFSET navigates to UTC before casting to DateTime2, preserving high precision.
Using AT TIME ZONE for precision
From SQL Server 2016, the AT TIME ZONE function can convert to UTC:
The AT TIME ZONE function brings DateTimeOffset to DateTime, matched to UTC.
Preserving precision with DateTime2
Keep precision by converting to DateTime2 before shifting to DateTime:
With CONVERT use style 126 to keep full precision when changing to DateTime:
Understanding local times and UTC
Converting dates and times isn't always as simple as it appears. The nuances of local and UTC times can impact your results.
Handling local time differences
To compare local times, use GETUTCDATE() to get the current UTC time:
Managing server timezone differences
Find the server's timezone offset with DATEPART and tz:
Always remember to adjust for server timezone differences to prevent incorrect conversions.
Verifying conversion
Your tests need to be as thorough as a detective novel plot. Use different DateTimeOffset values and consider the quirks of daylight saving and leap seconds:
Automate your testing to compare expected and actual DateTime results.
Was this article helpful?