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

查看:56
本文介绍了将日期时间转换为 Unix 时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

正如 Peter Halasz 在 T-SQL 日期时间到 Unix 时间戳:

<块引用>

将日期时间转换为 unix 时间戳很容易,但涉及错误倾向于输入以下内容:

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

其中@datetime 是您要转换的日期时间值.{d‘yyyy-mm-dd’} 表示法是 ODBC 转义序列.

功能:

CREATE FUNCTION UNIX_TIMESTAMP (@ctimestamp 日期时间)返回整数作为开始/* 函数体 */声明@return 整数SELECT @return = DATEDIFF(SECOND,{d '1970-01-01'}, @ctimestamp)返回@return结尾

现在像下面这样试试@O A:

<块引用>

SELECT UNIX_TIMESTAMP(GETDATE());

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?

解决方案

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 @O A:

SELECT UNIX_TIMESTAMP(GETDATE());

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

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