js timestamp与datetime之间的相互转换

1.  datetime转换成timestamp

strdate = " 2015-08-09 08:01:36: 789";
var d = new Date(strdate);
var timestamp= Math.round(d. getTime());
document.write("timestamp: "+timestamp+"
");
输出:
timestamp:  1439078496789
其他方法:
var timestamp = Date.parse(strdate);
或者
var timestamp = d.valueOf();
注意:
strdate要加上毫秒,不然再转换成datetime会丢失毫秒

2.  timestamp转换成datetime

function  timeStamp2String (time){
        var datetime = new Date();
         datetime.setTime(time);
         var year = datetime.getFullYear();
         var month = datetime.getMonth() + 1;
         var date = datetime.getDate();
         var hour = datetime.getHours();
         var minute = datetime.getMinutes();
         var second = datetime.getSeconds();
         var mseconds = datetime.getMilliseconds();
         return year + "-" + month + "-" + date+" "+hour+":"+minute+":"+second+"."+mseconds;
};
var time = " 1439078496789"; //or time=1439018115000; 结果一样
var strdate2 = timeStamp2String(time);
document.write("date: "+strdate2+"
");
输出:
date:  2015-8-9 8:1:36.789

你可能感兴趣的:(Web应用)