在 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

相关推荐
微风中的麦穗3 小时前
【MATLAB】MATLAB R2025a 详细下载安装图文指南:下一代科学计算与工程仿真平台
开发语言·matlab·开发工具·工程仿真·matlab r2025a·matlab r2025·科学计算与工程仿真
2601_949146534 小时前
C语言语音通知API示例代码:基于标准C的语音接口开发与底层调用实践
c语言·开发语言
开源技术4 小时前
Python Pillow 优化,打开和保存速度最快提高14倍
开发语言·python·pillow
学嵌入式的小杨同学4 小时前
从零打造 Linux 终端 MP3 播放器!用 C 语言实现音乐自由
linux·c语言·开发语言·前端·vscode·ci/cd·vim
mftang5 小时前
Python 字符串拼接成字节详解
开发语言·python
jasligea6 小时前
构建个人智能助手
开发语言·python·自然语言处理
yuezhilangniao6 小时前
AI智能体全栈开发工程化规范 备忘 ~ fastAPI+Next.js
javascript·人工智能·fastapi
kokunka6 小时前
【源码+注释】纯C++小游戏开发之射击小球游戏
开发语言·c++·游戏
云栖梦泽7 小时前
易语言开发从入门到精通:补充篇·网络编程进阶+实用爬虫开发·API集成·代理IP配置·异步请求·防封禁优化
开发语言
java1234_小锋7 小时前
Java高频面试题:SpringBoot为什么要禁止循环依赖?
java·开发语言·面试