Convert Datetime to Unix timestamp

蹲街弑〆低调 提交于 2019-12-04 18:58:05

问题


In Microsoft SQL Server 2012 or above, is it possible to convert a datetime value to Unix time stamp in a single select statement? If so, how can it be done?


回答1:


As Peter Halasz mentions in T-SQL DateTime to Unix Timestamp:

Converting a datetime to unix timestamp is easy, but involves error prone typing the following:

@timestamp=DATEDIFF(second,{d '1970-01-01'},@datetime)

Where @datetime is the datetime value you want to convert. The {d ‘yyyy-mm-dd’} notation is an ODBC escape sequence.

The function:

CREATE FUNCTION UNIX_TIMESTAMP (
@ctimestamp datetime
)
RETURNS integer
AS
BEGIN
  /* Function body */
  declare @return integer

  SELECT @return = DATEDIFF(SECOND,{d '1970-01-01'}, @ctimestamp)

  return @return
END

Try it out now like below @Ousman :

SELECT UNIX_TIMESTAMP(GETDATE());


来源:https://stackoverflow.com/questions/34455408/convert-datetime-to-unix-timestamp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!