Tsql DATETIME ISO 8601
Want a quick DATETIME
conversion to ISO 8601 in T-SQL? No problem! Use:
This will provide you an output like "2023-03-16T14:28:23"
, neatly formatted using ISO 8601.
The necessary 'CONVERT'ion
In most cases, representing dates and times in SQL Server refers to the ISO 8601 format (either standard or extended), with the optional time zone:
- Standard: 'YYYYMMDDTHHMMSS' or 'YYYYMMDDTHHMMSSZ'
- Extended: 'YYYY-MM-DDTHH:MM:SS' or 'YYYY-MM-DDTHH:MM:SSZ' // very important for pretty-printing
TheCONVERT
function, trusted sidekick of any SQL developer, is your go-to for this task. Use it with either style 126 (time) or style 127 (time zone):
Considering performance
Performance is a beast of burden when dealing with large data sets, and it's a 'no-no' to upset it. So, even though the FORMAT
function may seem tempting, remember, it's available only from from T-SQL 2012 and later.
Instead, handle conversions elegantly using CONVERT
with styles 126/127. Your performance metrics will thank you, and we may even throw in a medal 🏅! Here's a sneak peek at how to do it:
Let's not forget our date(time) etiquette
Storing dates is an equivalent of your SQL high school dating scene — tricky and full of standards. Store them using SQL Server's DATETIME
types, and only play the formatting game when you want to display them (dealing with angry breakups isn't fun, trust us!).
Storing formatted dates is like double texting — it's uncool and impairs query performance, indexing, and calculations.
'YMD' — the universal language of love (or at least in TSQL)
Dating is all about communication, isn't it? Well, in SQL Server, it's YMD
or YYYY-MM-DD
that everyone understands, making it language-neutral for date insertion:
Who wants some timezone awareness?
Tired of timezone mix-ups ruining your data consistency? Enter DATETIMEOFFSET
, the knight in shining armor, with your timezone offset right alongside your date and time data:
Was this article helpful?