前两天在公司项目中遇到一个需求,通过GET方式下载文件,其中路由中的一个字段就是时间戳,而前端需要把用户日期时间转换成时间戳来使用。在此之前,还真不知道时间戳是个神马东东。废话少说,直入正题!
什么是时间戳?
时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数。通俗的讲, 时间戳是一份能够表示一份数据在一个特定时间点已经存在的完整的可验证的数据。 它的提出主要是为用户提供一份电子证据, 以证明用户的某些数据的产生时间。 在实际应用上, 它可以使用在包括电子商务、 金融活动的各个方面, 尤其可以用来支撑公开密钥基础设施的 “不可否认” 服务。(引用自百度百科:https://baike.baidu.com/item/时间戳/6439235?fr=aladdin)
时间与时间戳相互转换
(1)、时间转时间戳
// 精确到秒
let date = time
date = new Date(Date.parse(date.replace(/-/g, '/')))
date = date.getTime()
return date
// 精确到毫秒,其实就是对上面结果再除以1000
let date = time
date = new Date(Date.parse(date.replace(/-/g, '/')))
date = date.getTime()
return date/1000
另一种写法
// 精确到秒(以s为单位)
function getTimeStamp() {
var date = Date.parse(new Date())
date = date / 1000
return date
}
方法3:
function getTimeStamp() {
return new Date().getTime(); // 获取了当前毫秒(ms)的时间戳,结果:1280977330748
// or
return (new Date()).valueOf(); // 获取了当前毫秒(ms)的时间戳, 结果:1280977330748
// or
return Date.parse(new Date()); // 获取的时间戳是把毫秒改成000显示,因为这种方式只精确到秒。结果:1280977330000
}
注意:经过本人测试,1与2返回的结果不一样。
(2)、时间戳转时间
1、转换成 2011-3-16 16:50:43 格式:
function getDate(tm) {
var tt = new Date(parseInt(tm) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ")
return tt;
}
2、转换成 2011年3月16日 16:50:43:
function getDate(tm){
var tt = new Date(parseInt(tm) * 1000).toLocaleString()
return tt;
}
3、转换成 2011年3月16日 16:50
function getDate(tm) {
var tt = new Date(parseInt(tm) * 1000).toLocaleString().substr(0,16);
return tt;
}