无论是前端或者后端在编写逻辑的过程中都会用到时间戳这个东西
一般我用时间戳,来命名一些上传的文件或者图片地址,比如之前做过的小程序项目图片上传到七牛云,为了避免图片地址的重复。
时间戳有两种精确方式一种是13位毫秒级别和10位秒级别写法如下:
Date.parse(new Date())时间戳是13位的后面是000为毫秒数除以1000为秒数
new Date().getTime();获取精确到毫秒
new Date()是获取当前最新的时间
今天突然想到一个问题就是时间戳转换成日期的问题。方法如下
timestampToTime(timestamp) {
var date = new Date(timestamp * 1000);//时间戳为10位需*1000,时间戳为13位的话不需乘1000
var Y = date.getFullYear() + '-';
var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
var D = (date.getDate() < 10 ? '0'+(date.getDate()) : date.getDate()) + ' ';
var h = (date.getHours()+1 < 10 ? '0'+(date.getHours()+1) : date.getHours()+1) + ':';
var m = (date.getMinutes()+1 < 10 ? '0'+(date.getMinutes()+1) : date.getMinutes()+1) + ':';
var s = (date.getSeconds()+1 < 10 ? '0'+(date.getSeconds()+1) : date.getSeconds()+1);
return Y+M+D+h+m+s;
}
return出来的就是日期