JS 時間戳轉日期格式

来源:互联网 发布:苹果电脑win7换mac 编辑:程序博客网 时间:2024/05/22 03:16
1、日期轉換為時間戳,(如果日期格式為時間戳,將其轉為日期類型,否則輸出傳入的數據)
// 如果時間格式為時間戳,將其轉為日期function timestampToDate(timestamp) {// 將數據類型轉為字符串if (timestamp && /^[0-9]*[0-9][0-9]*$/.test(timestamp) && (timestamp.toString().length == 10 || timestamp.toString().length == 13)) {timestamp = parseInt(timestamp);if (timestamp.toString().length == 10) {timestamp = timestamp * 1000;}var date = new Date(timestamp);Y = date.getFullYear();M = (date.getMonth() + 1 < 10 ? '0'+(date.getMonth() + 1) : date.getMonth() + 1);D = date.getDate();return Y+"-"+M+"-"+D;}return timestamp;}

2、時間戳轉換為日期

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Date对象</title></head><body><script> var date = new Date(1398250549123); //传个时间戳过去就可以了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()+ ':'; ss = date.getMilliseconds();console.log(Y+M+D+h+m+s+ss);  //2014-04-23 18:55:49:123</script></body></html>

日期轉換為時間戳

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Date对象</title></head><body><script>   var date = new Date('2014-04-23 18:55:49:123');//可以传时间,也可以不传,不传的话就是默认的当前时间  time1 = date.getTime();   time2 = date.valueOf();      time3 = Date.parse(date);  console.log(time1);  //1398250549123  console.log(time2);  //1398250549123  console.log(time3);  //1398250549000</script></body>


0 0
原创粉丝点击