SQL Server Unix Timestamp Guide: DATEDIFF_BIG & DATEADD
Running DATEADD(MILLISECOND, 1764892800000, '1970-01-01') in SQL Server crashes with Msg 8115: Arithmetic overflow error converting expression to data type int. Classic T-SQL date functions cap inputs at 32-bit integers, which breaks 13-digit milliseconds and future dates past 2038.
Get Current Unix Seconds and Milliseconds in T-SQL
Always use SYSUTCDATETIME() instead of GETDATE() so your query never depends on the local timezone of the Windows server. Use DATEDIFF_BIG() instead of DATEDIFF() because standard DATEDIFF overflows at roughly 24 days when counting milliseconds, as documented in the Microsoft Learn DATEDIFF_BIG reference.
-- Current Unix seconds (10 digits, BIGINT)
SELECT DATEDIFF_BIG(SECOND, '1970-01-01', SYSUTCDATETIME()) AS unix_sec;
-- Current Unix milliseconds (13 digits, BIGINT)
SELECT DATEDIFF_BIG(MILLISECOND, '1970-01-01', SYSUTCDATETIME()) AS unix_ms;
Convert Unix Seconds and Milliseconds to DATETIME2
Always cast the base epoch string to DATETIME2(3) or DATETIME2(0). Older DATETIME rounds milliseconds to increments of 3.33 ms, which corrupts exact log comparisons.
On SQL Server 2022 and earlier, DATEADD only accepts a 32-bit INT (max 2,147,483,647). To convert 13-digit milliseconds or dates past 2038 safely without overflow, split the value into whole days and remaining seconds:
DECLARE @UnixMs BIGINT = 1764892800123;
DECLARE @Seconds BIGINT = @UnixMs / 1000;
DECLARE @RemMs INT = @UnixMs % 1000;
SELECT DATEADD(MILLISECOND, @RemMs,
DATEADD(SECOND, @Seconds % 86400,
DATEADD(DAY, @Seconds / 86400, CAST('1970-01-01' AS DATETIME2(3)))
)
) AS utc_datetime;
Note that SQL Server 2025 adds direct BIGINT support to DATEADD, though splitting by days keeps your scripts portable across older enterprise databases too.
Best Practices for T-SQL Epoch Queries
- Use
DATETIME2(3)for storage: Avoid legacyDATETIMEin new tables. - Keep UTC consistent: Store UTC values in the database and convert to user timezones in the application layer.
- Watch Year 2038 limits: Never store Unix seconds inside a standard
INTcolumn. Read our Year 2038 Problem guide for migration tips.