SQL 将日期时间转换为 Unix 时间戳
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34455408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert Datetime to Unix timestamp
提问by O A
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?
在 Microsoft SQL Server 2012 或更高版本中,是否可以在单个 select 语句中将日期时间值转换为 Unix 时间戳?如果是这样,怎么做?
回答by khaled4vokalz
As Peter Halasz mentions in T-SQL DateTime to Unix Timestamp:
正如 Peter Halasz 在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());
将日期时间转换为 unix 时间戳很容易,但输入以下内容很容易出错:
@timestamp=DATEDIFF(second,{d '1970-01-01'},@datetime)
其中@datetime 是您要转换的日期时间值。{d 'yyyy-mm-dd'} 表示法是 ODBC 转义序列。
功能:
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:
SELECT UNIX_TIMESTAMP(GETDATE());