相关文章推荐
爱旅游的绿豆  ·  vars.put和vars.putObjec ...·  5 月前    · 
爱玩的鸡蛋面  ·  ComboBox 类 ...·  11 月前    · 
傲视众生的佛珠  ·  android ...·  1 年前    · 
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 (