// 示例代码:将 JavaScript 的 Date 对象格式化为常见的日期时间字符串
function formatDate(date) {
// 获取年份,月份(+1是因为JavaScript中月份从0开始),日期
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');
// 返回格式化的日期时间字符串,格式为:YYYY-MM-DD HH:MM:SS
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
// 创建一个新的 Date 对象
const now = new Date();
// 调用 formatDate 函数并打印结果
console.log(formatDate(now));
getFullYear():获取四位数的年份。getMonth():获取月份(0 表示一月,11 表示十二月),因此需要加 1。getDate():获取当前日期。getHours()、getMinutes() 和 getSeconds():分别获取小时、分钟和秒。String(...).padStart(2, '0'):确保输出的时间部分是两位数,不足两位时前面补零。YYYY-MM-DD HH:MM:SS。上一篇:js 时间对比
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站