How can I convert bigint (UNIX timestamp) to datetime in SQL Server?
Here's your fast track to convert a UNIX timestamp (bigint) to datetime in SQL Server:
Sprinkle this snippet in your SQL Server and the datatable will churn out the transformed datetime
in UTC. π
Arithmetic overflow: a case for large unicorns (UNIX timestamps)
Are you dealing with a UNIX timestamp that could remind some of Y2K? For timestamps representing dates post-2038 or when experiencing an arithmetic overflow, you might want to split your calculation to overcome the over-eager SQL Server:
Now, wave goodbye to overflow problems! π
Local timezone: Because Time is Local!
To correctly consider the timezone when conversing with your UNIX Timestamp, calculate the local offset and tweak your faithful timestamp:
Time to enjoy a locally brewed DateTime! β
Reusable Function: Save the world! Reuse!
Here's a magic charm encapsulated in a user-defined function for our conversion party. Because why should you have to remember this logic over and over again, right?
Behold the function! Now, getting your DateTime is as easy as this:
In-the-trenches tips and tricks
- Sing the UTC anthem always. Use UTC dates consistently to avoid timezone inconsistencies.
- Double-check '1970-01-01' to confirm it's in
YYYYMMDD
format. - Keep an eye on the results, especially with future-dated timestamps, to confirm that arithmetic overflow doesn't sneak in unnoticed.
- Modular arithmetic is your best friend for timestamps with a date beyond 2038.
DateTime to UNIX timestamp: Back to the FutUNIX
Fancy a DateTime trip back to UNIX epoch seconds? Let's spin that time machine in reverse:
Remember to mind any DateTime input formatting to nullify any conversion troubles.
Was this article helpful?