在 JavaScript 中,你可以使用 Date 对象来获取 当前日期 和 当前时间、当前年份。

在 JavaScript 中,你可以使用 Date 对象来获取 当前日期当前时间,以下是具体方法和示例代码:


1. 获取当前日期

使用 Date 对象的方法获取 年、月、日,并可以格式化为常见的日期字符串。

方法:
复制代码
const now = new Date(); // 创建 Date 对象,包含当前日期和时间

// 获取年、月、日(注意月份从 0 开始,需要 +1)
const year = now.getFullYear();  // 2025(四位年份)
const month = now.getMonth() + 1; // 6(实际是 6 月,但 getMonth() 返回 5)
const day = now.getDate();       // 9(当月的第几天)

// 格式化为 YYYY-MM-DD
const formattedDate = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
console.log(formattedDate); // 输出:2025-06-09

2. 获取当前时间

使用 Date 对象的方法获取 时、分、秒、毫秒,并可格式化为时间字符串。

方法:
复制代码
const hours = now.getHours();     // 当前小时(0-23)
const minutes = now.getMinutes(); // 当前分钟(0-59)
const seconds = now.getSeconds(); // 当前秒(0-59)

// 格式化为 HH:MM:SS
const formattedTime = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
console.log(formattedTime); // 例如:14:30:45(根据当前时间)

3. 同时获取日期和时间

可以直接用 toLocaleString() 或自定义格式组合:

示例:
复制代码
// 方法1:使用 toLocaleString(依赖系统区域设置)
console.log(now.toLocaleString()); // 输出:2025/6/9 14:30:45(格式可能因系统而异)

// 方法2:自定义拼接
console.log(`当前时间:${formattedDate} ${formattedTime}`); // 输出:2025-06-09 14:30:45

4. 其他常用方法

  • now.toISOString() → 返回 ISO 格式的日期时间(UTC 时区),例如 "2025-06-09T06:30:45.000Z"

  • now.toLocaleDateString() → 仅返回本地格式的日期(如 "2025/6/9")。

  • now.toLocaleTimeString() → 仅返回本地格式的时间(如 "14:30:45")。

    const now = new Date();

    // 获取日期
    const date = ${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')};

    // 获取时间
    const time = ${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')};

    console.log(当前日期:${date}); // 2025-06-09
    console.log(当前时间:${time}); // 14:30:45
    console.log(日期和时间:${date} ${time}); // 2025-06-09 14:30:45

注意事项:

  • 月份从 0 开始getMonth() 返回 0(1月)到 11(12月),所以需要 +1

  • 补零操作 :用 padStart(2, '0') 确保个位数显示为 0102 等。

  • 时区问题 :以上方法均基于用户本地时区,如需 UTC 时间,可用 getUTC 系列方法(如 getUTCHours())。

如果需要更复杂的日期处理(如加减日期、时区转换),推荐使用库如 moment.jsdate-fns

相关推荐
小羊没烦恼!2 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
三十而立洋2 天前
Cookie 详解:从产生到安全,一次讲透
前端·javascript
伞伞悦读2 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
卡布鲁2 天前
把一个 Vite + Vue3 应用塞进 qiankun (React + Umi3) 主站:十个坑的复盘
前端·javascript·react.js
C语言小火车2 天前
C/C++ 为什么需要编译器?
开发语言·c++
李少兄2 天前
JavaScript 隐式全局变量解析
javascript
霍霍的袁2 天前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio
孙启超2 天前
【AI开发之Rust】第 11 课:智能指针与内部可变性
开发语言·后端·rust
此生决int2 天前
深入理解C++系列(20)——C++11(下)
开发语言·c++
沙蒿同学2 天前
我用 Go 搭了一条 AI Agent 流水线:从 1 张商品图到一整套淘宝详情页
前端·javascript·后端