js获取当前日期时间及其它操作

在 JavaScript 中,处理"当前日期和时间"是非常常见的需求,通常通过 Date 对象实现。以下是你可能会用到的典型操作合集,涵盖当前时间获取、格式化、加减时间、比较、时间戳转换等。


1. 获取当前日期时间

javascript 复制代码
const now = new Date();
console.log(now); // 示例:2025-08-03T09:41:20.123Z
php
72 Bytes
© 菜鸟-创作你的创作

2. 获取年/月/日/小时/分钟/秒

javascript 复制代码
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}`);
php
372 Bytes
© 菜鸟-创作你的创作

3. 获取当前时间戳

javascript 复制代码
const timestamp = Date.now(); // 毫秒数
console.log(timestamp); // 示例:1754262080123
php
80 Bytes
© 菜鸟-创作你的创作

4. 时间加减操作(如当前时间+1天)

vbscript 复制代码
const now = new Date();
const tomorrow = new Date(now.getTime() + 24 * 60 * 60 * 1000); // 加一天
console.log(tomorrow.toString());
php
129 Bytes
© 菜鸟-创作你的创作

你也可以加小时、分钟等:

vbscript 复制代码
// 加2小时
const twoHoursLater = new Date(now.getTime() + 2 * 60 * 60 * 1000);
php
75 Bytes
© 菜鸟-创作你的创作

5. 时间格式化函数(返回 yyyy-mm-dd hh:mm:ss

javascript 复制代码
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()));
php
422 Bytes
© 菜鸟-创作你的创作

6. 时间戳转日期

javascript 复制代码
const date = new Date(1754262080123);
console.log(date.toLocaleString()); // 根据本地格式显示
php
85 Bytes
© 菜鸟-创作你的创作

7. 日期字符串转时间戳

vbscript 复制代码
const timestamp = new Date("2025-08-03 18:30:00").getTime();
console.log(timestamp); // 输出对应时间戳
php
95 Bytes
© 菜鸟-创作你的创作

8. 日期比较

javascript 复制代码
const a = new Date('2025-08-01');
const b = new Date('2025-08-03');
if (a < b) {
  console.log("a 早于 b");
}
php
108 Bytes
© 菜鸟-创作你的创作

附:使用 dayjsmoment.js(更简洁)

安装 dayjs(推荐轻量库)

复制代码
npm install dayjs
php
17 Bytes
© 菜鸟-创作你的创作

示例:

less 复制代码
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')); // true
php
212 Bytes
© 菜鸟-创作你的创作

好的,下面是一个浏览器可直接运行 的 HTML 页面,内含完整的 JS 脚本,你只需复制以下代码到本地 .html文件中打开即可查看效果,或直接在浏览器开发者工具中运行 JS。


完整示例:获取当前时间、格式化、加减、比较、时间戳等

xml 复制代码
<!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>
php
1.72 KB
© 菜鸟-创作你的创作

功能亮点:

  • 获取当前时间(原始和格式化)
  • 显示年、月、日、时、分、秒
  • 获取当前时间戳
  • 时间加一天
  • 时间戳 ↔️ 日期互转
  • 日期比较

如果你还需要实现:

  • 定时器(setInterval 实时更新时间)
  • 倒计时或时间差计算
  • 使用 Day.js 或 Moment.js 美化

我可以在这个 Demo 基础上扩展一个小"时间工具页面"。是否需要?

下面是一个可在浏览器直接打开的完整时间工具页面,包含以下功能:


功能列表:

  1. 实时显示当前时间(每秒更新)
  2. 时间戳 ↔️ 日期字符串互转
  3. 计算两个日期之间的时间差(天数)
  4. 日期加减工具(+/- 天数)
  5. 所有结果动态显示

一键复制以下 HTML 保存为 time-tools.html 即可运行:

xml 复制代码
<!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>
php
3.83 KB
© 菜鸟-创作你的创作

使用方法:

  1. 把上面代码复制为 time-tools.html
  2. 双击打开浏览器
  3. 即可使用所有时间工具,无需联网,无依赖

www.52runoob.com/archives/51...

相关推荐
ZLlllllll01 分钟前
常见的框架漏洞(Thinkphp,spring,Shiro)
java·后端·spring·常见的框架漏洞
ZS88512 分钟前
【AI】 Clickhouse MergeTree基本原理
后端
陈随易43 分钟前
为VSCode扩展开发量身打造的UI库 - vscode-elements
前端·后端·程序员
Always_July1 小时前
java如何使用函数式编程优雅处理根据ID设置Name
后端
uhakadotcom1 小时前
Docker 入门教程
后端·面试·github
冒泡的肥皂1 小时前
2PL-事务并发控制
数据库·后端·mysql
天天摸鱼的java工程师1 小时前
面试必问的JVM垃圾收集机制详解
java·后端·面试
ajack2 小时前
SpringBoot 1.5.4 版本和SpringBoot 2.7.18 在kafka重平衡对消费线程的处理方式略有差异
后端
树獭叔叔2 小时前
Node.js 多进程与多线程:从原理到实践
后端·node.js