将Datetime转换为Unix时间戳 [英] Convert Datetime to Unix timestamp

查看:205
本文介绍了将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());


这篇关于将Datetime转换为Unix时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆