可以使用 JavaScript 中的 Date
對象對時間戳進(jìn)行格式化轉(zhuǎn)換。具體的實現(xiàn)方式可以按照以下步驟進(jìn)行:
-
將時間戳轉(zhuǎn)換為日期對象。JavaScript 中可以使用
new Date(timestamp)
方法將時間戳轉(zhuǎn)換為日期對象,timestamp 為時間戳。 -
使用日期對象的
getYear()
、getMonth()
、getDate()
、getHours()
、getMinutes()
、getSeconds()
等方法獲取年、月、日、時、分、秒等時間單位。 -
拼接需要的時間格式。
下面是一個時間戳轉(zhuǎn)換為指定格式日期的實例代碼:
function formatDate(timestamp, format) {
// 將時間戳轉(zhuǎn)換為日期對象
const date = new Date(timestamp);
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
// 替換需要的時間格式
format = format.replace('yyyy', year);
format = format.replace('MM', month < 10 ? '0' + month : month);
format = format.replace('dd', day < 10 ? '0' + day : day);
format = format.replace('HH', hours < 10 ? '0' + hours : hours);
format = format.replace('mm', minutes < 10 ? '0' + minutes : minutes);
format = format.replace('ss', seconds < 10 ? '0' + seconds : seconds);
return format;
}
// 示例代碼
console.log(formatDate(1619097074830, 'yyyy-MM-dd HH:mm:ss')); // 2021-04-22 18:57:54
在上面的代碼中,我們定義了一個 formatDate 函數(shù),接收兩個參數(shù):時間戳和格式字符串。使用 new Date(timestamp)
方法將時間戳轉(zhuǎn)換為日期對象后,再使用日期對象的各種方法獲取年、月、日、時、分、秒等時間單位,最后使用字符串的替換方法將格式字符串中的占位符替換為實際的時間值,從而生成指定格式的日期字符串。文章來源:http://www.zghlxwxcb.cn/news/detail-744606.html
這樣就實現(xiàn)了一個簡單的時間戳格式化函數(shù),可以根據(jù)需要修改格式字符串,實現(xiàn)更多的時間格式轉(zhuǎn)換。文章來源地址http://www.zghlxwxcb.cn/news/detail-744606.html
到了這里,關(guān)于將時間戳按格式轉(zhuǎn)換為日期對象的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!