在 JavaScript 中,处理“当前日期和时间”是非常常见的需求,通常通过 Date
对象实现。以下是你可能会用到的典型操作合集,涵盖当前时间获取、格式化、加减时间、比较、时间戳转换等。
1. 获取当前日期时间
const now = new Date();console.log(now); // 示例:2025-08-03T09:41:20.123Zphp72 Bytes© 菜鸟-创作你的创作
2. 获取年/月/日/小时/分钟/秒
const now = new Date();const year = now.getFullYear(); // 年const month = now.getMonth() + 1; // 月(注意:从 0 开始,所以要 +1)const date = now.getDate(); // 日const hour = now.getHours(); // 小时const minute = now.getMinutes(); // 分钟const second = now.getSeconds(); // 秒console.log(`${year}-${month}-${date} ${hour}:${minute}:${second}`);php372 Bytes© 菜鸟-创作你的创作
3. 获取当前时间戳
const timestamp = Date.now(); // 毫秒数console.log(timestamp); // 示例:1754262080123php80 Bytes© 菜鸟-创作你的创作
4. 时间加减操作(如当前时间+1天)
const now = new Date();const tomorrow = new Date(now.getTime() + 24 * 60 * 60 * 1000); // 加一天console.log(tomorrow.toString());php129 Bytes© 菜鸟-创作你的创作
你也可以加小时、分钟等:
// 加2小时const twoHoursLater = new Date(now.getTime() + 2 * 60 * 60 * 1000);php75 Bytes© 菜鸟-创作你的创作
5. 时间格式化函数(返回 yyyy-mm-dd hh:mm:ss
)
function formatDate(date) { const y = date.getFullYear(); const m = String(date.getMonth() + 1).padStart(2, '0'); const d = String(date.getDate()).padStart(2, '0'); const h = String(date.getHours()).padStart(2, '0'); const min = String(date.getMinutes()).padStart(2, '0'); const s = String(date.getSeconds()).padStart(2, '0'); return `${y}-${m}-${d} ${h}:${min}:${s}`;}console.log(formatDate(new Date()));php422 Bytes© 菜鸟-创作你的创作
6. 时间戳转日期
const date = new Date(1754262080123);console.log(date.toLocaleString()); // 根据本地格式显示php85 Bytes© 菜鸟-创作你的创作
7. 日期字符串转时间戳
const timestamp = new Date("2025-08-03 18:30:00").getTime();console.log(timestamp); // 输出对应时间戳php95 Bytes© 菜鸟-创作你的创作
8. 日期比较
const a = new Date('2025-08-01');const b = new Date('2025-08-03');if (a < b) { console.log("a 早于 b");}php108 Bytes© 菜鸟-创作你的创作
附:使用 dayjs
或 moment.js
(更简洁)
dayjs
(推荐轻量库)npm install dayjsphp17 Bytes© 菜鸟-创作你的创作
import dayjs from 'dayjs';console.log(dayjs().format('YYYY-MM-DD HH:mm:ss')); // 当前时间console.log(dayjs().add(1, 'day').format()); // 明天console.log(dayjs('2025-08-01').isBefore('2025-08-03')); // truephp212 Bytes© 菜鸟-创作你的创作
好的,下面是一个浏览器可直接运行的 HTML 页面,内含完整的 JS 脚本,你只需复制以下代码到本地 .html
文件中打开即可查看效果,或直接在浏览器开发者工具中运行 JS。
完整示例:获取当前时间、格式化、加减、比较、时间戳等
<!DOCTYPE html><html><head> <meta charset="UTF-8"> <title>JS 时间操作演示</title></head><body> <h2>JavaScript 时间处理 Demo</h2> <pre id="output"></pre> <script> const output = []; // 1. 当前时间 const now = new Date(); output.push("当前时间对象: " + now); // 2. 分解日期 output.push("年: " + now.getFullYear()); output.push("月: " + (now.getMonth() + 1)); output.push("日: " + now.getDate()); output.push("时: " + now.getHours()); output.push("分: " + now.getMinutes()); output.push("秒: " + now.getSeconds()); // 3. 时间戳 const timestamp = Date.now(); output.push("当前时间戳: " + timestamp); // 4. 格式化 function formatDate(date) { const y = date.getFullYear(); const m = String(date.getMonth() + 1).padStart(2, '0'); const d = String(date.getDate()).padStart(2, '0'); const h = String(date.getHours()).padStart(2, '0'); const min = String(date.getMinutes()).padStart(2, '0'); const s = String(date.getSeconds()).padStart(2, '0'); return `${y}-${m}-${d} ${h}:${min}:${s}`; } output.push("格式化时间: " + formatDate(now)); // 5. 时间加一天 const tomorrow = new Date(now.getTime() + 24 * 60 * 60 * 1000); output.push("明天同一时间: " + formatDate(tomorrow)); // 6. 比较两个日期 const d1 = new Date('2025-08-01'); const d2 = new Date('2025-08-03'); output.push("2025-08-01 是否早于 2025-08-03: " + (d1 < d2)); // 7. 时间戳转日期 const tsToDate = new Date(1754262080123); output.push("从时间戳生成时间: " + formatDate(tsToDate)); // 8. 字符串转时间戳 const strToTs = new Date("2025-08-03 20:00:00").getTime(); output.push("字符串转时间戳: " + strToTs); // 显示在页面上 document.getElementById('output').textContent = output.join('\n'); </script></body></html>php1.72 KB© 菜鸟-创作你的创作
功能亮点:
获取当前时间(原始和格式化)
显示年、月、日、时、分、秒
获取当前时间戳
时间加一天
时间戳 ↔️ 日期互转
日期比较
如果你还需要实现:
setInterval
实时更新时间)我可以在这个 Demo 基础上扩展一个小“时间工具页面”。是否需要?
下面是一个可在浏览器直接打开的完整时间工具页面,包含以下功能:
功能列表:
一键复制以下 HTML 保存为 time-tools.html
即可运行:
<!DOCTYPE html><html lang="zh"><head> <meta charset="UTF-8"> <title>JavaScript 时间工具</title> <style> body { font-family: "Arial", sans-serif; padding: 20px; line-height: 1.8; } h2 { color: #3366cc; } input, button { padding: 5px 10px; margin: 5px 0; } .section { margin-bottom: 30px; border-bottom: 1px solid #ddd; padding-bottom: 20px; } .output { background: #f4f4f4; padding: 10px; border-radius: 5px; } </style></head><body> <h1> JavaScript 时间工具合集</h1> <div class="section"> <h2> 实时当前时间</h2> <div class="output" id="clock">加载中...</div> </div> <div class="section"> <h2> 时间戳 ↔️ 日期字符串</h2> <div> <label>时间戳 ➜ 日期:</label> <input type="number" id="tsInput" placeholder="如 1754262080123"> <button onclick="convertToDate()">转换</button> <div class="output" id="tsToDateOut"></div> </div> <div> <label>日期 ➜ 时间戳:</label> <input type="text" id="dateInput" placeholder="如 2025-08-03 20:00:00"> <button onclick="convertToTs()">转换</button> <div class="output" id="dateToTsOut"></div> </div> </div> <div class="section"> <h2> 两个日期之间相差几天</h2> <input type="date" id="diffStart"> ➜ <input type="date" id="diffEnd"> <button onclick="calcDiff()">计算</button> <div class="output" id="diffResult"></div> </div> <div class="section"> <h2> 日期加/减天数</h2> <label>起始日期:</label> <input type="date" id="baseDate"> <label>加/减天数:</label> <input type="number" id="offset" value="1"> <button onclick="addDays()">计算</button> <div class="output" id="addResult"></div> </div> <script> // 1. 实时时钟 function formatDate(date) { const y = date.getFullYear(); const m = String(date.getMonth() + 1).padStart(2, '0'); const d = String(date.getDate()).padStart(2, '0'); const h = String(date.getHours()).padStart(2, '0'); const min = String(date.getMinutes()).padStart(2, '0'); const s = String(date.getSeconds()).padStart(2, '0'); return `${y}-${m}-${d} ${h}:${min}:${s}`; } function updateClock() { document.getElementById('clock').textContent = formatDate(new Date()); } setInterval(updateClock, 1000); updateClock(); // 2. 时间戳转日期 function convertToDate() { const ts = document.getElementById('tsInput').value; if (!ts) return; const date = new Date(Number(ts)); document.getElementById('tsToDateOut').textContent = formatDate(date); } // 日期转时间戳 function convertToTs() { const dateStr = document.getElementById('dateInput').value; const date = new Date(dateStr); if (isNaN(date.getTime())) { document.getElementById('dateToTsOut').textContent = " 日期格式无效"; } else { document.getElementById('dateToTsOut').textContent = date.getTime(); } } // 3. 计算日期差 function calcDiff() { const start = new Date(document.getElementById('diffStart').value); const end = new Date(document.getElementById('diffEnd').value); if (isNaN(start.getTime()) || isNaN(end.getTime())) { document.getElementById('diffResult').textContent = " 请选择两个有效日期"; return; } const diffMs = Math.abs(end - start); const days = Math.floor(diffMs / (1000 * 60 * 60 * 24)); document.getElementById('diffResult').textContent = `相差 ${days} 天`; } // 4. 日期加减天数 function addDays() { const base = new Date(document.getElementById('baseDate').value); const offset = parseInt(document.getElementById('offset').value); if (isNaN(base.getTime())) { document.getElementById('addResult').textContent = " 起始日期无效"; return; } const newDate = new Date(base.getTime() + offset * 24 * 60 * 60 * 1000); document.getElementById('addResult').textContent = `结果日期:${formatDate(newDate)}`; } </script></body></html>php3.83 KB© 菜鸟-创作你的创作
使用方法:
time-tools.html
https://www.52runoob.com/archives/5197
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。