js 時間戳格式化日期格式


時間戳轉換為日期,網上搜了好幾個或多或少都有點問題,自己整理了一下,寫了個方法

 

console.log(formatDate(1565280000000))

輸出:

 2019-08-09 00:00:00

 

Date.prototype.format =function(datetime)
{
       var date = new Date(datetime);//時間戳為10位需*1000,時間戳為13位的話不需乘1000
                var year = date.getFullYear(),
                    month = ("0" + (date.getMonth() + 1)).slice(-2),
                    sdate = ("0" + date.getDate()).slice(-2),
                    hour = ("0" + date.getHours()).slice(-2),
                    minute = ("0" + date.getMinutes()).slice(-2),
                    second = ("0" + date.getSeconds()).slice(-2);
                // 拼接
                var result = year + "-"+ month +"-"+ sdate +" "+ hour +":"+ minute +":" + second;
                // 返回
                return result;
}

 

 

formatDate(datetime) {
                var date = new Date(datetime);//時間戳為10位需*1000,時間戳為13位的話不需乘1000
                var year = date.getFullYear(),
                    month = ("0" + (date.getMonth() + 1)).slice(-2),
                    sdate = ("0" + date.getDate()).slice(-2),
                    hour = ("0" + date.getHours()).slice(-2),
                    minute = ("0" + date.getMinutes()).slice(-2),
                    second = ("0" + date.getSeconds()).slice(-2);
                // 拼接
                var result = year + "-"+ month +"-"+ sdate +" "+ hour +":"+ minute +":" + second;
                // 返回
                return result;
            }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM