JS時間戳與日期格式的轉換小結
更新時間:2024年01月20日 10:38:02 作者:NCDS程序員
這篇文章主要介紹了JS時間戳與日期格式的轉換小結,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧
JS時間戳與日期格式的轉換
1、將時間戳轉換成日期格式:
function timestampToTime(timestamp) {
// 時間戳為10位需*1000,時間戳為13位不需乘1000
var date = new Date(timestamp * 1000);
var Y = date.getFullYear() + "-";
var M =
(date.getMonth() + 1 < 10
? "0" + (date.getMonth() + 1)
: date.getMonth() + 1) + "-";
var D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
var h = date.getHours() + ":";
var m = date.getMinutes() + ":";
var s = date.getSeconds();
return Y + M + D + h + m + s;
}
console.log(timestampToTime(1670145353)); //2022-12-04 17:15:532、將日期格式轉換成時間戳:
var date = new Date("2022-12-04 17:15:53:555");
// 有三種方式獲取
var time1 = date.getTime();
var time2 = date.valueOf();
var time3 = Date.parse(date);
console.log(time1); //1670145353555
console.log(time2); //1670145353555
console.log(time3); //1670145353000js基礎之Date對象以及日期和時間戳的轉換
js中使用Date對象來表示時間和日期:
獲取年月日時分秒和星期等
var now = new Date(); now; now.getFullYear(); // 2021, 年份 now.getMonth(); // 2, 月份,月份范圍是0~11,2表示3月 now.getDate(); // 4, 表示4號 now.getDay(); // 3, 星期三 now.getHours(); // 16, 表示19h now.getMinutes(); // 41, 分鐘 now.getSeconds(); // 22, 秒 now.getMilliseconds(); // 473, 毫秒數 now.getTime(); // 1614847074473, 以number形式表示的時間戳
創(chuàng)建指定日期的時間對象
var d = new Date(2021, 3, 4, 16, 15, 30, 123);
將日期解析為時間戳
var d = Date.parse('2021-03-04 16:49:22.123');
d; // 1614847762123
// 嘗試更多方式
(new Date()).valueOf();
new Date().getTime();
Number(new Date()); 時間戳轉日期
var d = Date.parse('2021-03-04 16:49:22.123');
d; // 1614847762123
// 嘗試更多方式
(new Date()).valueOf();
new Date().getTime();
Number(new Date()); 時間戳轉自定義格式的日期
因為操作系統(tǒng)或者瀏覽器顯示格式的不確定性,固定格式的日期只能自己拼接:
function getDate() {
var now = new Date(),
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);
}
getDate() // "2021-03-04 16:56:39"到此這篇關于JS時間戳與日期格式的轉換的文章就介紹到這了,更多相關js時間戳與日期轉換內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
深入了解JavaScript中l(wèi)et/var/function的變量提升
這篇文章主要介紹了深入了解JavaScript中l(wèi)et/var/function的變量提升,文章圍繞主題展開詳細的內容介紹,具有一定的參考價值,需要的朋友可以參考一下2022-07-07
JS IOS/iPhone的Safari瀏覽器不兼容Javascript中的Date()問題如何解決
這篇文章主要介紹了JS IOS/iPhone的Safari瀏覽器不兼容Javascript中的Date()問題的解決方案,非常不錯,感興趣的朋友參考下吧2016-11-11
使用?TypeScript?開發(fā)?React?函數式組件
這篇文章主要介紹了使用?TypeScript開發(fā)React函數式組件,文章通過圍繞主題展開詳細的內容介紹,具有一定的參考價值,感興趣的小伙伴可以參考一下2022-08-08

