js与es6中获取时间戳

在项目中经常会用到求时间戳的问题,下面是已经封装好的函数,直接使用就可以。
1.js常用获取时间戳的方法

// 获取时间戳
var start = new Date().getTime();
console.log(start);
var end = '1553321456632'; console.log(timediff(start,end)); function timediff(begin_time, end_time) {
if (begin_time < end_time) {
starttime = begin_time;
endtime = end_time;
}else {
starttime = end_time;
endtime = begin_time;
}
//计算天数 1s=1000ms
var timediff = parseInt((endtime - starttime) / 1000);
var days = parseInt(timediff / 86400);
//计算小时数
var remain = (timediff % 86400);
var hours = parseInt(remain / 3600);
//计算分钟数
var remain = remain % 3600;
var mins = parseInt(remain / 60);
//计算秒数 if((remain % 60) <= 9){
var secs = '0'+remain % 60;
}else{
var secs = remain % 60;
}
var res = days + "天" + hours + "时" + mins + "分" + secs + "秒";
var res1 = hours+":"+mins + ":" + secs;
var res2 = mins + ":" + secs;
var res3 = secs;
return res;//需要什么格式的时间戳,就return 出 res2等
}

  同时,在es6中获取时间戳的写法,如下。其中在es6的方法中函数之间的调用 使用的是 this.funName(); 并且可以传递参数

//函数1;获取开始于结束时间
getTimes:function(){//时间戳
let start = new Date().getTime();
console.log(start);
let end = '1553321456632';
console.log(this.timediff(start,end));
},
//调用时间戳,得出想要的时间戳格式
timediff(begin_time,end_time){
let starttime,endtime,timediff,days,remain,hours,mins,secs;
if (begin_time < end_time) {
starttime = begin_time;
endtime = end_time;
}else {
starttime = end_time;
endtime = begin_time;
}
//计算天数 1s=1000ms
timediff = parseInt((endtime - starttime) / 1000);
days = parseInt(timediff / 86400);
//计算小时数
remain = (timediff % 86400);
hours = parseInt(remain / 3600);
//计算分钟数
remain = remain % 3600;
mins = parseInt(remain / 60);
//计算秒数
if((remain % 60) <= 9){
secs = '0'+remain % 60;
}else{
secs = remain % 60;
}
let res = days + "天" + hours + "时" + mins + "分" + secs + "秒";
let res1 = hours+":"+mins + ":" + secs;
let res2 = mins + ":" + secs;
let res3 = secs;
//res,res1,res2,res3为你想返回的数据格式,比如返回时:分:秒格式 return res1
return res+';需要的时间戳格式:'+res1; }

  

上一篇:手把手教你自定义attr


下一篇:c语言贪吃蛇详解5.GameOver功能与显示成绩