简单弄一个format
时间:2024-3-19 10:41 作者:suxiaojun 分类: 无
/**
- @description 格式化时间
- @param {number/String} timestamp 时间戳(毫秒)
- @param {string} formatString 想要返回的格式
-
@returns {string} - 格式化后的日期字符串
*/
export const format = (timestamp, formatString) => {
const date = new Date(timestamp);
const year = date.getFullYear();
const month = padZero(date.getMonth() + 1); // 月份是从0开始的,所以需要加1
const day = padZero(date.getDate());
const hours = padZero(date.getHours());
const minutes = padZero(date.getMinutes());
const seconds = padZero(date.getSeconds());// 填充前导零的函数
function padZero(number) {
return number.toString().padStart(2, '0');
}// 替换格式字符串中的占位符
return formatString
.replace('yyyy', year)
.replace('MM', month)
.replace('dd', day)
.replace('hh', hours)
.replace('mm', minutes)
.replace('ss', seconds);
}
第二种方法
// utils/formatDate.js
export function formatDate(timestamp) {
const date = new Date(timestamp);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
return ${year}-${month}-${day} ${hours}:${minutes}:${seconds}
;
}