// 获取当前时间的年月日
function getCurrentDate() {
// 创建一个新的 Date 对象,获取当前时间
const now = new Date();
// 获取当前年份
const year = now.getFullYear();
// 获取当前月份(注意:getMonth() 返回的是 0-11,所以需要加 1)
const month = now.getMonth() + 1;
// 获取当前日期
const day = now.getDate();
// 返回格式化的年月日字符串,确保月份和日期都是两位数
return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
}
// 调用函数并输出结果
console.log(getCurrentDate());
这段代码定义了一个 getCurrentDate 函数,用于获取当前的年、月、日,并以 YYYY-MM-DD 的格式返回。使用了 JavaScript 的 Date 对象来获取当前时间,并通过 getFullYear()、getMonth() 和 getDate() 方法分别获取年、月、日。为了确保月份和日期是两位数,使用了 String.prototype.padStart() 方法进行填充。
上一篇:js 多个数组合并
下一篇:js date获取年月日
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站