時間字符串&時間戳轉換


// 獲取當前時間
var time = Date.parse(new Date()) / 1000; //方法一(這種方法只精確到秒) eg:1621580943000/1000
var time = (new Date()).valueOf() / 1000; //方法二(獲取當前毫秒時間戳) eg:1621581019132/1000
var time = new Date().getTime() / 1000; //方法三(獲取當前毫秒時間戳) eg:1621581090367/1000

// 時間字符串轉時間戳的兩種方法
var time = '2020-06-30 00:00:00';
1. time = new Date(Date.parse(time.replace(/-/g, "/"))).getTime() / 1000;
2. time = new Date(time).getTime() / 1000// 時間戳轉時間字符串
var time = '1566012105'
let stampLength = time.toString().length
let tstamp
if (stampLength == 10) {
    tstamp = new Date(stamp * 1000)
} else if (stampLength == 13) {
    tstamp = new Date(stamp)
} else if (stampLength == 19) {
    tstamp = new Date(stamp)
} else {
    console.warn('GetFormatTime warn: 請傳入正確的時間戳')
    return
}

let year = tstamp.getFullYear(tstamp)
let month = tstamp.getMonth(tstamp) + 1
let day = tstamp.getDate(tstamp)
let hour = tstamp.getHours(tstamp)
let minute = tstamp.getMinutes(tstamp)
let second = tstamp.getSeconds(tstamp)
if (month < 10) {
    month = '0' + month
}
if (day < 10) {
    day = '0' + day
}
if (hour < 10) {
    hour = '0' + hour
}
if (minute < 10) {
    minute = '0' + minute
}
if (second < 10) {
    second = '0' + second
}
return `${year}-${month}-${day} ${hour}:${minute}:${second}`
 

 


免責聲明!

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



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