// 获取当前时间的年月日时分秒
function getCurrentDateTime() {
// 创建一个新的 Date 对象,获取当前时间
const now = new Date();
// 获取年份
const year = now.getFullYear();
// 获取月份(注意:getMonth() 返回的是 0-11,所以需要加 1)
const month = String(now.getMonth() + 1).padStart(2, '0');
// 获取日期
const day = String(now.getDate()).padStart(2, '0');
// 获取小时(24 小时制)
const hours = String(now.getHours()).padStart(2, '0');
// 获取分钟
const minutes = String(now.getMinutes()).padStart(2, '0');
// 获取秒数
const seconds = String(now.getSeconds()).padStart(2, '0');
// 返回格式化的日期和时间字符串
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
// 调用函数并打印结果
console.log(getCurrentDateTime());
Date 对象:使用 new Date() 获取当前时间。getFullYear() 方法获取四位数的年份。getMonth() 返回的是 0-11 的整数,因此需要加 1。为了确保月份始终是两位数,使用了 String().padStart(2, '0') 来补零。getDate() 获取当前日期,并同样使用 padStart 确保日期为两位数。getHours()、getMinutes() 和 getSeconds() 获取当前的小时、分钟和秒数,并确保它们都是两位数。如果你调用 getCurrentDateTime() 函数,它会输出类似 2023-10-05 14:30:45 这样的格式。
上一篇:js contains
下一篇:js 获取昨天的日期
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站