// 获取当前日期并格式化输出
// 使用 new Date() 创建一个新的日期对象,表示当前日期和时间
const currentDate = new Date();
// 获取年份
const year = currentDate.getFullYear();
// 获取月份(注意:getMonth() 返回的月份是从0开始的,所以需要加1)
const month = currentDate.getMonth() + 1;
// 获取日期
const day = currentDate.getDate();
// 格式化输出日期为 "YYYY-MM-DD" 格式
const formattedDate = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
console.log(formattedDate); // 输出格式化的日期
new Date():创建一个表示当前日期和时间的 Date 对象。getFullYear():获取四位数的年份。getMonth():获取月份,返回值是 0 到 11,因此需要加 1。getDate():获取当前月份中的日期(1 到 31)。padStart(2, '0'):确保月份和日期始终是两位数,不足两位时前面补零。`${}` 来拼接字符串,使代码更简洁。这段代码会输出当前日期,格式为 YYYY-MM-DD。
上一篇:js 当前时间戳
下一篇:js 获取本地ip
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站