JS時間戳與日期格式的轉(zhuǎn)換小結(jié)
JS時間戳與日期格式的轉(zhuǎn)換
1、將時間戳轉(zhuǎn)換成日期格式:
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、將日期格式轉(zhuǎn)換成時間戳:
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基礎(chǔ)之Date對象以及日期和時間戳的轉(zhuǎn)換
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, 毫秒數(shù) 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()); 時間戳轉(zhuǎn)日期
var d = Date.parse('2021-03-04 16:49:22.123');
d; // 1614847762123
// 嘗試更多方式
(new Date()).valueOf();
new Date().getTime();
Number(new Date()); 時間戳轉(zhuǎn)自定義格式的日期
因為操作系統(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"到此這篇關(guān)于JS時間戳與日期格式的轉(zhuǎn)換的文章就介紹到這了,更多相關(guān)js時間戳與日期轉(zhuǎn)換內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
BootstrapValidator實現(xiàn)表單驗證功能
這篇文章主要為大家詳細介紹了BootstrapValidator實現(xiàn)表單驗證功能,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-11-11
javascript實現(xiàn)Table間隔色以及選擇高亮(和動態(tài)切換數(shù)據(jù))的方法
這篇文章主要介紹了javascript實現(xiàn)Table間隔色以及選擇高亮(和動態(tài)切換數(shù)據(jù))的方法,涉及javascript表格操作及按鈕實現(xiàn)表格切換的技巧,需要的朋友可以參考下2015-05-05

