// 获取当前的年月日时分秒
// 创建一个新的 Date 对象,它会包含当前的日期和时间
let now = new Date();
// 获取年份
let year = now.getFullYear(); // 完整的四位数年份
// 获取月份 (0-11), 需要加1转换成常规的1-12
let month = now.getMonth() + 1;
// 获取日期 (1-31)
let day = now.getDate();
// 获取小时 (0-23)
let hours = now.getHours();
// 获取分钟 (0-59)
let minutes = now.getMinutes();
// 获取秒数 (0-59)
let seconds = now.getSeconds();
// 将获取到的时间格式化为两位数(例如:01, 02, ..., 12)
month = month < 10 ? '0' + month : month;
day = day < 10 ? '0' + day : day;
hours = hours < 10 ? '0' + hours : hours;
minutes = minutes < 10 ? '0' + minutes : minutes;
seconds = seconds < 10 ? '0' + seconds : seconds;
// 输出格式化的年月日时分秒
console.log(`${year}-${month}-${day} ${hours}:${minutes}:${seconds}`);
这段代码通过 Date 对象获取当前的年、月、日、时、分、秒,并将其格式化为类似 YYYY-MM-DD HH:MM:SS 的字符串形式。
上一篇:js 获取当前年月日时分秒
下一篇:js 获取年月
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站