简体   繁体   English

将日期时间转换为 Unix 时间戳

[英]Convert Datetime to Unix timestamp

In Microsoft SQL Server 2012 or above, is it possible to convert a datetime value to Unix time stamp in a single select statement?在 Microsoft SQL Server 2012 或更高版本中,是否可以在单个 select 语句中将日期时间值转换为 Unix 时间戳? If so, how can it be done?如果是这样,怎么办?

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:将 datetime 转换为 unix timestamp 很容易,但输入以下内容时容易出错:

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

Where @datetime is the datetime value you want to convert. @datetime 是您要转换的日期时间值。 The {d 'yyyy-mm-dd'} notation is an ODBC escape sequence. {d 'yyyy-mm-dd'} 符号是 ODBC 转义序列。

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 @OA:现在像下面@OA 一样尝试一下:

 SELECT UNIX_TIMESTAMP(GETDATE());

maybe this answer will help someone... If you have a problem when you try to convert datetime using datediff function to number of seconds (mssql message: The datediff function resulted in an overflow. The number of dateparts separating two date/time instances is too large. Try to use datediff with a less precise datepart.) then use:也许这个答案会对某人有所帮助...如果您在尝试使用 datediff 函数将 datetime 转换为秒数时遇到问题(mssql 消息:datediff 函数导致溢出。分隔两个日期/时间实例的 dateparts 的数量是太大。尝试将 datediff 与不太精确的日期部分一起使用。)然后使用:

select cast(datediff(d,'1970-01-01',@d1) as bigint)*86400+datediff(s,dateadd(day, datediff(day, 0, @d1), 0),@d1)

if you have ms sql server 2016+ use DATEDIFF_BIG function如果你有 ms sql server 2016+ 使用 DATEDIFF_BIG 函数

my function with localization我的本地化功能

CREATE FUNCTION UNIX_TIMESTAMP(@ctimestamp datetime)
RETURNS integer
AS
begin
  return DATEDIFF(second,'1970-01-01',GETUTCDATE())+datediff(second,GETDATE(),@ctimestamp)
end

then i use value in js code然后我在js代码中使用值

new Date(unixSec*1000)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM