SQL server 时间戳 (timestamp) 与时间格式 (datetime) 互转

SQL server 时间戳 (timestamp) 与时间格式 (datetime) 互转

时间戳就是一个从 1970-01-01 00:00:00 到时间的相隔的秒数。

所以只要把这个时间戳加上 1970-01-01 08:00:00 这个时间就可以得到你想要的时间了。

select DATEADD(second,1562477826 + 8 * 60 * 60,'1970-01-01 00:00:00')

北京时间与 GMT 时间关系

  • GMT 是中央时区, 北京在东 8 区, 相差 8 个小时   
  • 所以北京时间 = GMT 时间 + 八小时

DATEADD() 函数: 在日期中添加或减去指定的时间间隔。返回完整时间。

  • DATEADD(datepart,number,date)
  • date参数是合法的日期表达式。number是您希望添加的间隔数;对于未来的时间,此数是正数,对于过去的时间,此数是负数。
sleect getdate()
select DATEADD(day,2,getdate())

示例:

/*创建表*/
create table vbu_plus_test 
(
id int  not null ,--ID
mzh varchar(20) primary key not null,--购买标识(人)
bdate varchar(20),--购买时间
edate varchar(20)--有效期截止时间
)

/*插入数据(一部分)*/
INSERT INTO vbu_plus_test (id, mzh, bdate, edate) VALUES
(10,	'MZ00045598',	1561935295,	1625049147),
(12,	'MZ00112886',	1561957137,	1593514063),
(13,	'MZ00114981',	1561958172,	1625072024),
(14,	'MZ00119996',	1561969499,	1593526425),
(16,	'MZ00120167',	1562039364,	1593596290),
(17,	'MZ00094773',	1562112432,	1593669358);

/*查询:查询一段时间内每天购买此商品的人次。
这里将varchar() 转换成int ,这里如果当初建表时,格式为int,也不不需要次步骤;
用dateadd() 函数将时间戳转换成普通时间;
在用convert() 将时间格式化为1990-01-01;
利用到row_number()over() 生成id,这个貌似多此一举;
*/
declare 
@sdate datetime,
@edate datetime

set @sdate='2019-07-01 00:00:00'
set @edate='2019-07-09 00:00:00'

select count(ids), convert(varchar(100),bdate, 23) from (
select ROW_NUMBER()over(partition by convert(varchar(100),DATEADD(S,CAST(bdate as int) + 8 * 3600,'1970-01-01 00:00:00'), 23) order by mzh) ids,
ID,mzh, DATEADD(S,CAST(bdate as int) + 8 * 3600,'1970-01-01 00:00:00')  bdate,
DATEADD(S,CAST(edate as int) + 8 * 3600,'1970-01-01 00:00:00')  edate 
from vbu_plus_test ) a
where bdate between @sdate and @edate
group by convert(varchar(100),bdate, 23)
  • 普通时间转换成时间戳
SELECT DATEDIFF(S,'1970-01-01 08:00:00', GETDATE())       -- 普通时间转换成时间戳

编辑于 2022-11-16 11:54・IP 属地北京