Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js 获取日期

作者:饮尽孤单   发布日期:2026-05-13   浏览:124

// 获取当前日期并格式化输出

// 使用 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); // 输出格式化的日期

解释说明:

  1. new Date():创建一个表示当前日期和时间的 Date 对象。
  2. getFullYear():获取四位数的年份。
  3. getMonth():获取月份,返回值是 0 到 11,因此需要加 1。
  4. getDate():获取当前月份中的日期(1 到 31)。
  5. padStart(2, '0'):确保月份和日期始终是两位数,不足两位时前面补零。
  6. 模板字符串:使用反引号 `${}` 来拼接字符串,使代码更简洁。

这段代码会输出当前日期,格式为 YYYY-MM-DD

上一篇:js 当前时间戳

下一篇:js 获取本地ip

大家都在看

js 数组打乱顺序

js 两个数组取交集

js 数组对象排序

js 对象数组排序

js 数组删掉第一个值

js fill

js fill方法

js 数组连接

js json数组

js 数组复制

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站