JavaScript如何將時間戳轉(zhuǎn)化為年月日時分秒格式
首先獲取到當前的時間戳或者需要轉(zhuǎn)化為時間的時間戳
var time = new Date(時間戳); //得到Thu May 11 2023 15:22:41 GMT+0800 (中國標準時間) //這種樣式的時間但是不是我們想要的所以要繼續(xù)處理
然后使用getFullYear、getMonth、 getDate、getHours、getMinutes、getSeconds等方法來獲取當前時間的年月日時分秒
var y=time.getFullYear();//返回年份 //getMonth方法從 Date 對象返回月份 (0 ~ 11),返回結(jié)果需要手動加一var d = time.getDate(); // getDate方法從 Date 對象返回一個月中的某一天 (1 ~ 31) var M=time.getMonth()+1; var d=time.getDate(); var h=time.getHours(); var m = time.getMinutes(); var s = times.getSeconds();
最后使用字符串拼接的方式得到我們想要的時間
var times = y + '-' + M + '-' + d + ' ' + h + ':' + m + ':' + s //得到這種格式2023-5-11 15:32:29
如果往后端傳時間有嚴格要求必須是0000-00-00 00:00:00這種格式再做處理
if (M <= 9) {
M = '0' + M
}
if (d <= 9) {
d = '0' + d
}
if (h <= 9) {
h = '0' + h
}
if (m <= 9) {
m = '0' + m
}
if (s <= 9) {
s = '0' + s
}
//得到這種格式2023-05-11 15:35:35附:自定義方法轉(zhuǎn)換
getYMDHMS (timestamp) {
let time = new Date(timestamp)
let year = time.getFullYear()
let month = time.getMonth() + 1
let date = time.getDate()
let hours = time.getHours()
let minute = time.getMinutes()
let second = time.getSeconds()
if (month < 10) { month = '0' + month }
if (date < 10) { date = '0' + date }
if (hours < 10) { hours = '0' + hours }
if (minute < 10) { minute = '0' + minute }
if (second < 10) { second = '0' + second }
return year + '-' + month + '-' + date + ' ' + hours + ':' + minute + ':' + second
}
// 使用es6的padStart()方法來補0
getYMDHMS (timestamp) {
let time = new Date(timestamp)
let year = time.getFullYear()
const month = (time.getMonth() + 1).toString().padStart(2, '0')
const date = (time.getDate()).toString().padStart(2, '0')
const hours = (time.getHours()).toString().padStart(2, '0')
const minute = (time.getMinutes()).toString().padStart(2, '0')
const second = (time.getSeconds()).toString().padStart(2, '0')
return year + '-' + month + '-' + date + ' ' + hours + ':' + minute + ':' + second
}
總結(jié)
到此這篇關于JavaScript如何將時間戳轉(zhuǎn)化為年月日時分秒格式的文章就介紹到這了,更多相關JS時間戳轉(zhuǎn)為年月日時分秒內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
使用BootStrap建立響應式網(wǎng)頁——通欄輪播圖(carousel)
這篇文章主要介紹了使用BootStrap建立響應式網(wǎng)頁通欄輪播圖(carousel)的相關資料,需要的朋友可以參考下2016-12-12
layui 實現(xiàn)table翻頁滾動條位置保持不變的例子
今天小編就為大家分享一篇layui 實現(xiàn)table翻頁滾動條位置保持不變的例子,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-09-09
JS+CSS實現(xiàn)超漂亮的動態(tài)翻書效果(思路詳解)
我們平常沖浪時是不是看過一些學校高級的錄取通知書,翻開通知書就能看見里面的內(nèi)容,呈現(xiàn)出逼真的3D效果,本文帶領大家基于JS+CSS實現(xiàn)超漂亮的動態(tài)翻書效果,需要的朋友可以參考下2023-05-05

