Click here to Skip to main content
15,885,309 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
i have a epoch data : 1535525060000
i need to convert this into IST as Wednesday, August 29,2018 12:14:20 PM GMT+05:30 in sql server. How can i achieve this?

Pleasde help me on this

What I have tried:

ALTER FUNCTION [dbo].[fn_EpochToDatetime] (@Epoch BIGINT)
RETURNS DATETIME
AS
BEGIN
    DECLARE @Days AS INT, @MilliSeconds AS INT
    SET @Days = @Epoch / (1000*60*60*24)
    SET @MilliSeconds = @Epoch % (1000*60*60*24)

    RETURN (SELECT DATEADD(MILLISECOND, @MilliSeconds, DATEADD(DAY, @Days, '1/1/1970')))
END;


SELECT  [dbo].[fn_EpochToDatetime] (153552506000)
Posted
Updated 15-Nov-22 1:06am

1 solution

The SQL datetime type does not have a "UTC offset" value.

Your code returns a UTC datetime, which is correctly set to 2018-08-29 06:44:20. If you want to convert that to a different timezone, you're going to need to use a timezone-aware type: the datetimeoffset.
SQL
CREATE OR ALTER FUNCTION dbo.fn_EpochToDateTimeOffset (@Epoch bigint)
RETURNS datetimeoffset(0)
As
BEGIN
    DECLARE @Days int, @Milliseconds int, @Utc datetimeoffset(0);
    SET @Days = @Epoch / (1000 * 60 * 60 * 24);
    SET @Milliseconds = @Epoch % (1000 * 60 * 60 * 24);
    SET @Utc = DateAdd(millisecond, @Milliseconds, DateAdd(day, @Days, '19700101'));
    Return @Utc At Time Zone 'India Standard Time';
END;
GO
SELECT dbo.fn_EpochToDateTimeOffset(153552506000);
/* 2018-08-29 12:14:20 +05:30 */
AT TIME ZONE (Transact-SQL) - SQL Server | Microsoft Learn[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900