时间与时间戳相互转化

var strtime='2018-06-23';
var date=new Date(strtime.replace(/-/g,'/'));
var time1=date.getTime();//2018-06-23的时间戳
 
// 有三种方式获取,三种方式的区别
 
//time1 = date.getTime();
//time2 = date.valueOf();
//time3 = Date.parse(date);
//第一、第二种:会精确到毫秒
//第三种:只能精确到秒,毫秒将用0来代替

 

var Newdate=new Date().getTime();//当前时间戳
var a=time1-Newdate;//计算剩余天数
console.log(Math.floor(a/86400000));
 

Date()参数形式有7种

new Date( "month dd,yyyy hh:mm:ss" );
new Date( "month dd,yyyy" );
new Date( "yyyy/MM/dd hh:mm:ss" );
new Date( "yyyy/MM/dd" );
new Date(yyyy,mth,dd,hh,mm,ss);
new Date(yyyy,mth,dd);
new Date(ms);
 
当前时间戳转化为yyyy-MM-dd 格式时间
var Newdate=new Date().getTime();
console.log(Newdate.toLocaleDateString().replace(/\//g,'-')+' '+Newdate.toTimeString().substr(0,8));
方法二
var date=new Date();
Y = date.getFullYear() + '-';
M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) :
date.getMonth()+1) + '-';
D = date.getDate() + ' ';
h = date.getHours() + ':';
m = date.getMinutes() + ':';
s = date.getSeconds();
console.log(Y+M+D+h+m+s);//yyyy-MM-dd hh:mm:ss
 

猜你喜欢

转载自www.cnblogs.com/caoruichun/p/9211235.html