js将时间戳格式化为yy-mm-dd hh:mm:ss
时间: 2023-09-07 18:15:55 浏览: 75
你可以使用以下方法将 JavaScript 的时间戳格式化为 "yy-mm-dd hh:mm:ss" 的格式:
```javascript
function formatDate(timestamp) {
// 将时间戳转换为 JavaScript Date 对象
const date = new Date(timestamp);
// 获取年、月、日、小时、分钟和秒
const year = date.getFullYear().toString().slice(-2); // 提取年份的后两位
const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始,需要加1,并且补零
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'); // 补零
// 构建格式化后的字符串
const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
return formattedDate;
}
// 示例使用
const timestamp = 1635798930000; // 假设时间戳为 1635798930000
console.log(formatDate(timestamp));
```
这将输出类似于 "21-11-01 09:28:50" 的格式化日期和时间字符串。你可以根据需要进行调整和修改。