// 将时间戳转换为指定格式的日期字符串
function formatDate(timestamp, format = 'yyyy-MM-dd hh:mm:ss') {
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 format.replace('yyyy', year)
.replace('MM', month)
.replace('dd', day)
.replace('hh', hours)
.replace('mm', minutes)
.replace('ss', seconds);
}
// 示例用法
const timestamp = Date.now(); // 获取当前时间戳
console.log(formatDate(timestamp)); // 输出类似:2023-10-05 14:30:45
formatDate 函数:接收两个参数,一个是时间戳 timestamp,另一个是可选的格式化字符串 format。默认格式为 'yyyy-MM-dd hh:mm:ss'。new Date(timestamp):将时间戳转换为 Date 对象。getYear, getMonth, getDate, getHours, getMinutes, getSeconds:这些方法用于从 Date 对象中提取年、月、日、时、分、秒。String(...).padStart(2, '0'):确保月份、日期、小时、分钟和秒数都是两位数,不足两位的前面补零。replace 方法:根据传入的格式字符串,替换其中的占位符(如 yyyy, MM, dd 等)为实际的时间值。这样就可以根据需要灵活地格式化时间了。
上一篇:js 时间格式转换
下一篇:js escape函数
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站