欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

javascript獲取時(shí)間戳的5種方法詳解

 更新時(shí)間:2023年03月17日 14:19:04   作者:小馬大咖  
這篇文章主要介紹了javascript獲取時(shí)間戳的5種方法詳解,本文通過示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

js/javascript獲取時(shí)間戳的5種方法

1.獲取時(shí)間戳精確到秒,13位

const timestamp = Date.parse(new Date());
console.log(timestamp);
 
//輸出 1591669256000   13位

2.獲取時(shí)間戳精確到毫秒,13位

const timestamp = Math.round(new Date());
console.log(timestamp);
 
//輸出 1591669961203   13位

3.獲取時(shí)間戳精確到毫秒,13位

const timestamp = (new Date()).valueOf();
console.log(timestamp);
 
//輸出 1591670037603   13位
const timestamp = (new Date()).valueOf();
console.log(timestamp);
 
//輸出 1591670037603   13位

4.獲取時(shí)間戳精確到毫秒,13位

const timestamp = new Date().getTime();
console.log(timestamp);
 
//輸出 1591670068833   13位

5.獲取時(shí)間戳精確到毫秒,13位

const timestamp = +new Date();
console.log(timestamp);
 
//輸出 1591670099066   13位

其它

在開發(fā)的中需要精確到秒的時(shí)候,推薦使用 第1種方法,也需要除以1000才行,如果是需要時(shí)間戳毫秒的推薦 +new Date() 和 new Date().getTime();

補(bǔ)充:js時(shí)間戳轉(zhuǎn)時(shí)間

我們可以接用 new Date(時(shí)間戳) 格式轉(zhuǎn)化獲得當(dāng)前時(shí)間,比如:

new Date(1472048779952)
Wed Aug 24 2016 22:26:19 GMT+0800 (中國標(biāo)準(zhǔn)時(shí)間)

注意:時(shí)間戳參數(shù)必須是Number類型,如果是字符串,解析結(jié)果:Invalid Date。

如果后端直接返回時(shí)間戳給前端,前端如何轉(zhuǎn)換呢?下面介紹2種實(shí)現(xiàn)方式

方法一:生成'2022/1/18 上午10:09 '格式

function getLocalTime(n) { ??
? ?return new Date(parseInt(n)).toLocaleString().replace(/:\d{1,2}$/,' '); ??
} ??
getLocalTime(1642471746435) //'2022/1/18 上午10:09 '

也可以用如下,想取幾位就幾位,注意,空格也算!

function getLocalTime(n) { ??
? ? return new Date(parseInt(n)).toLocaleString().substr(0,14)
} ??
getLocalTime(1642471746435) //'2022/1/18 上午10'

或者利用正則:

function ?getLocalTime(n){
? ?return new Date(parseInt(n)).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
}
getLocalTime ?(1642471746435) ?//'2022/1/18 上午10:09:06'

方法二:生成'yyyy-MM-dd hh:mm:ss '格式

先轉(zhuǎn)換為data對(duì)象,然后利用拼接正則等手段來實(shí)現(xiàn):

function getData(n){
? n=new Date(n)
? return n.toLocaleDateString().replace(/\//g, "-") + " " + n.toTimeString().substr(0, 8)
}
getData(1642471746435) //'2022-1-18 10:09:06'

不過這樣轉(zhuǎn)換在某些瀏覽器上會(huì)出現(xiàn)不理想的效果,因?yàn)閠oLocaleDateString()方法是因?yàn)g覽器而異的,比如 IE為"2016年8月24日 22:26:19"格式 ;搜狗為"Wednesday, August 24, 2016 22:39:42"

可以通過分別獲取時(shí)間的年月日進(jìn)行拼接,這樣兼容性更好:

function getData(n) {
? let now = new Date(n),
? ? y = now.getFullYear(),
? ? m = now.getMonth() + 1,
? ? d = now.getDate();
? return y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d) + " " + now.toTimeString().substr(0, 8);
}
getData(1642471746435) //'2022-1-18 10:09:06'

到此這篇關(guān)于js/javascript獲取時(shí)間戳的5種方法的文章就介紹到這了,更多相關(guān)js獲取時(shí)間戳內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論