In SQL Server, there are two main methods to convert a datetimeoffset
to a string.
Using CONVERT Function
The CONVERT
function with style 121 is the most efficient method:
|
|
Important Note: When using CONVERT
, you must specify an adequate length for the nvarchar
parameter to accommodate the full datetimeoffset
value including fractional seconds and time zone offset [^1].
Using FORMAT Function
The FORMAT
function offers more flexibility with culture-specific formatting:
|
|
Format Styles
When using CONVERT, these are some common-style numbers for datetimeoffset
:
Style | Output Format |
---|---|
121 | yyyy-mm-dd hh:mi:ss.mmm(24h) |
126 | yyyy-mm-ddThh:mi:ss.mmm |
127 | yyyy-mm-ddThh:mi:ss.mmmZ |
The styles 121 and 126 are recommended, as it preserves the time zone offset information [^2].
For example:
|
|
will output:
|
|
You can use SQLiteOnline.com to test this with all major RBMS engines.
Sources I read on the topic
- [^1] : https://stackoverflow.com/questions/65823243/convert-datetimeoffset-to-varchar
- [^2] : https://www.dofactory.com/sql/convert-datetime-to-string
Follow me
Thanks for reading this article. Make sure to follow me on X, subscribe to my Substack publication and bookmark my blog to read more in the future.
Photo by Muffin Land