Millisecond-level Unix timestamp, convert it to date time format, error, "Arithmetic overflow error occurred when converting expression to data type int"

If you have a timestamp value of 1689217823000, representing a Unix timestamp in milliseconds, you can convert it to a datetime format. In SQL Server, you can use the DATEADD and CONVERT functions to convert.
Here are the steps to convert that timestamp value to datetime format:
DECLARE @timestamp bigint = 1689217823000;
DECLARE @datetime datetime;

SET @datetime = DATEADD(ms, @timestamp, '1970-01-01T00:00:00');
SET @datetime = DATEADD(HOUR, DATEDIFF(HOUR, GETUTCDATE(), GETDATE()), @datetime); - - Takes into account time zone differences

SELECT @datetime AS converted_datetime;

In this example, we first declare a variable @timestamp and set it to a timestamp value. Then, use the DATEADD function to add the millisecond-level timestamp to the starting date of the Unix timestamp (January 1, 1970) to get the converted datetime value.
To account for time zone differences, we also use the DATEADD and DATEDIFF functions to adjust the datetime value to match the time in the current time zone.
Finally, the converted datetime value @datetime is returned via the SELECT statement.
Note that time zone is an important factor, make sure proper time zone adjustments are taken into account during conversion. You can make corresponding adjustments according to your actual time zone conditions.

Execute the above example and report an error,

 

"Arithmetic overflow error occurred when converting expression to data type int", how to solve?

Let's try another way to solve this problem.

1. First, convert the timestamp value to bigint type. Assuming your timestamp value is 1689217823000:

DECLARE @timestamp bigint = 1689217823000;


2. Then, divide the converted timestamp value by 1000 to get a timestamp in seconds:

SET @timestamp = @timestamp / 1000;


3. Next, add the converted second-level timestamp value to the start date (January 1, 1970) to obtain the corresponding datetime value:

DECLARE @datetime datetime = DATEADD(ss, @timestamp, '1970-01-01T00:00:00');


4. Finally, the datetime value can be adjusted to account for time zone differences. Depending on your time zone, you can use the following code to adjust:

SET @datetime = DATEADD(HOUR, DATEDIFF(HOUR,GETUTCDATE(),CURRENT_TIMESTAMP), @datetime);

Note that this assumes that your time zone is the current system time zone. If your needs are not based on the current time zone, but adjust to a specific time zone, you will need to modify the above code accordingly.
Finally, you can check the converted datetime value with a SELECT statement:
SELECT @datetime as converted_datetime;

This method should successfully convert the timestamp value to datetime format without arithmetic overflow errors.

Guess you like

Origin blog.csdn.net/qq1507171150/article/details/131793428