Wednesday, May 7, 2008

Converting a DateTime value to a Unix Timestamp (ms sql server)

While trying to decode the ExtJs library, I came across a obstacle that the time format of Ext Library was Timestamp (unix) while my data was stored in DateTime format. After long hunt for solving this problem, I came across a page: http://mysql.databases.aspfaq.com/how-do-i-convert-a-sql-server-datetime-value-to-a-unix-timestamp.html

This page provided me the solution for my problem. The solution that I used was put this query in my DataAdapter: "select *, excerpt = left(postDesc,100), timestamp = DATEDIFF(s, '19700101', lastPost) from topic"

Here DATEDIFF(s, '19700101', lastPost) converts datetime into timestamp. The writer suggested that this method can convert dates upto 2038-01-19 at 3:14:08 AM only. The write also suggested the alternative function to get dates after above said date. The function is as:

CREATE FUNCTION dbo.DTtoUnixTS
(
@dt DATETIME
)
RETURNS BIGINT
AS
BEGIN
DECLARE @diff BIGINT
IF @dt >= '20380119'
BEGIN
SET @diff = CONVERT(BIGINT, DATEDIFF(S, '19700101', '20380119'))
+ CONVERT(BIGINT, DATEDIFF(S, '20380119', @dt))
END
ELSE
SET @diff = DATEDIFF(S, '19700101', @dt)
RETURN @diff
END


I think this is a great stuff

No comments: