将Datetime转换为Unix时间戳

将Datetime转换为Unix时间戳

问题描述:

在Microsoft SQL Server 2012或更高版本中,是否可以在单个select语句中将datetime值转换为Unix时间戳?如果是这样,怎么办呢?

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?

正如彼得·哈拉斯(Peter Halasz)在从T-SQL DateTime到Unix时间戳

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


将日期时间转换为unix时间戳很容易,但是容易出错,输入以下内容: p>

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

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

@datetime是要转换的日期时间值。 {d
'yyyy-mm-dd'}表示法是ODBC转义序列。

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

函数:

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

立即尝试以下@Ousman:

Try it out now like below @Ousman :

SELECT UNIX_TIMESTAMP(GETDATE());