// 获取当前年月日时分秒的示例代码
function getDateTime() {
// 创建一个新的 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');
// 获取小时
const hours = String(now.getHours()).padStart(2, '0');
// 获取分钟
const minutes = String(now.getMinutes()).padStart(2, '0');
// 获取秒数
const seconds = String(now.getSeconds()).padStart(2, '0');
// 拼接成 "YYYY-MM-DD HH:mm:ss" 格式的字符串
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
console.log(getDateTime());
new Date()
:创建一个表示当前日期和时间的 Date
对象。getFullYear()
:获取四位数的年份。getMonth()
:获取月份,返回值为 0 到 11,因此需要加 1。getDate()
:获取当前月份中的日期(1 到 31)。getHours()
:获取小时(0 到 23)。getMinutes()
:获取分钟(0 到 59)。getSeconds()
:获取秒数(0 到 59)。String(...).padStart(2, '0')
:确保月份、日期、小时、分钟和秒数都是两位数,不足两位时前面补零。上一篇:js 获取星期几
下一篇:js 获取年月
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站