最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用JavaScript獲取當(dāng)前日期時間及其它操作

 更新時間:2025年08月05日 09:19:25   作者:用戶151290545220  
在 JavaScript 中,處理“當(dāng)前日期和時間”是非常常見的需求,本文為大家詳細(xì)介紹了JavaScript 獲取當(dāng)前日期時間及其它操作,包括格式化,加減時間,時間戳轉(zhuǎn)換等

在 JavaScript 中,處理“當(dāng)前日期和時間”是非常常見的需求,通常通過 Date 對象實現(xiàn)。以下是你可能會用到的典型操作合集,涵蓋當(dāng)前時間獲取、格式化、加減時間、比較、時間戳轉(zhuǎn)換等。

1. 獲取當(dāng)前日期時間

const now = new Date();
console.log(now); // 示例:2025-08-03T09:41:20.123Z

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}`);

3. 獲取當(dāng)前時間戳

const timestamp = Date.now(); // 毫秒數(shù)
console.log(timestamp); // 示例:1754262080123

4. 時間加減操作(如當(dāng)前時間+1天)

const now = new Date();
const tomorrow = new Date(now.getTime() + 24 * 60 * 60 * 1000); // 加一天
console.log(tomorrow.toString());

你也可以加小時、分鐘等:

// 加2小時
const twoHoursLater = new Date(now.getTime() + 2 * 60 * 60 * 1000);

5. 時間格式化函數(shù)(返回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}-$wppm3vysvbp ${h}:${min}:${s}`;
}
console.log(formatDate(new Date()));

6. 時間戳轉(zhuǎn)日期

const date = new Date(1754262080123);
console.log(date.toLocaleString()); // 根據(jù)本地格式顯示

7. 日期字符串轉(zhuǎn)時間戳

const timestamp = new Date("2025-08-03 18:30:00").getTime();
console.log(timestamp); // 輸出對應(yīng)時間戳

8. 日期比較

const a = new Date('2025-08-01');
const b = new Date('2025-08-03');
if (a < b) {
  console.log("a 早于 b");
}

附:使用dayjs或moment.js(更簡潔)

安裝dayjs(推薦輕量庫)

npm install dayjs

示例

import dayjs from 'dayjs';
console.log(dayjs().format('YYYY-MM-DD HH:mm:ss'));  // 當(dāng)前時間
console.log(dayjs().add(1, 'day').format());         // 明天
console.log(dayjs('2025-08-01').isBefore('2025-08-03')); // true

好的,下面是一個瀏覽器可直接運行的 HTML 頁面,內(nèi)含完整的 JS 腳本,你只需復(fù)制以下代碼到本地 .html文件中打開即可查看效果,或直接在瀏覽器開發(fā)者工具中運行 JS。

完整示例:獲取當(dāng)前時間、格式化、加減、比較、時間戳等

<!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. 當(dāng)前時間
    const now = new Date();
    output.push("當(dāng)前時間對象: " + 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("當(dāng)前時間戳: " + 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}-$wppm3vysvbp ${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. 時間戳轉(zhuǎn)日期
    const tsToDate = new Date(1754262080123);
    output.push("從時間戳生成時間: " + formatDate(tsToDate));
    // 8. 字符串轉(zhuǎn)時間戳
    const strToTs = new Date("2025-08-03 20:00:00").getTime();
    output.push("字符串轉(zhuǎn)時間戳: " + strToTs);
    // 顯示在頁面上
    document.getElementById('output').textContent = output.join('\n');
  </script>
</body>
</html>

功能亮點

  •  獲取當(dāng)前時間(原始和格式化)
  •  顯示年、月、日、時、分、秒
  •  獲取當(dāng)前時間戳
  •  時間加一天
  •  時間戳<->日期互轉(zhuǎn)
  •  日期比較

如果你還需要實現(xiàn):

  • 定時器(setInterval 實時更新時間)
  • 倒計時或時間差計算
  • 使用 Day.js 或 Moment.js 美化

我可以在這個 Demo 基礎(chǔ)上擴(kuò)展一個小“時間工具頁面”。是否需要?

下面是一個可在瀏覽器直接打開的完整時間工具頁面,包含以下功能:

功能列表

  • 實時顯示當(dāng)前時間(每秒更新)
  • 時間戳<->日期字符串互轉(zhuǎn)
  • 計算兩個日期之間的時間差(天數(shù))
  • 日期加減工具(+/- 天數(shù))
  • 所有結(jié)果動態(tài)顯示

一鍵復(fù)制以下 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> 實時當(dāng)前時間</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()">轉(zhuǎn)換</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()">轉(zhuǎn)換</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> 日期加/減天數(shù)</h2>
    <label>起始日期:</label>
    <input type="date" id="baseDate">
    <label>加/減天數(shù):</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}-$wppm3vysvbp ${h}:${min}:${s}`;
    }
    function updateClock() {
      document.getElementById('clock').textContent = formatDate(new Date());
    }
    setInterval(updateClock, 1000);
    updateClock();
    // 2. 時間戳轉(zhuǎn)日期
    function convertToDate() {
      const ts = document.getElementById('tsInput').value;
      if (!ts) return;
      const date = new Date(Number(ts));
      document.getElementById('tsToDateOut').textContent = formatDate(date);
    }
    // 日期轉(zhuǎn)時間戳
    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. 日期加減天數(shù)
    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 = `結(jié)果日期:${formatDate(newDate)}`;
    }
  </script>
</body>
</html>

使用方法:

把上面代碼復(fù)制為 time-tools.html

雙擊打開瀏覽器

即可使用所有時間工具,無需聯(lián)網(wǎng),無依賴

到此這篇關(guān)于使用JavaScript獲取當(dāng)前日期時間及其它操作的文章就介紹到這了,更多相關(guān)JavaScript獲取當(dāng)前日期時間內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Js瀏覽器全屏代碼(模仿按F11)

    Js瀏覽器全屏代碼(模仿按F11)

    Js瀏覽器全屏代碼(模仿按F11),需要的朋友可以參考下。
    2011-01-01
  • 詳解自動生成博客目錄案例

    詳解自動生成博客目錄案例

    本文主要對自動生成博客目錄的具體實現(xiàn)方法進(jìn)行介紹,需要的朋友可以看看
    2016-12-12
  • 第五篇Bootstrap 排版

    第五篇Bootstrap 排版

    使用bootstrap的排版特性可以創(chuàng)建標(biāo)題,段落,列表及其它內(nèi)聯(lián)元素。本文重點給大家介紹Bootstrap 排版 知識,非常不錯,具有參考借鑒價值,感興趣的朋友一起學(xué)習(xí)吧
    2016-06-06
  • 由document.body和document.documentElement想到的

    由document.body和document.documentElement想到的

    不知道大家對這個標(biāo)題有沒有想法,反正此前我一直把他們混為了一談。其實不然,首先需有個“標(biāo)準(zhǔn)”的概念。
    2009-04-04
  • webpack中多文件打包配置的詳細(xì)流程

    webpack中多文件打包配置的詳細(xì)流程

    這篇文章主要介紹了webpack中多文件打包配置的詳細(xì)流程,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧
    2023-11-11
  • 用Javascript來生成ftp腳本的小例子

    用Javascript來生成ftp腳本的小例子

    昨天閑著沒事,又因為工作需要,寫了一個腳本,用來做ftp。當(dāng)然不是直接做ftp,而是產(chǎn)生一個ftp的腳本,供ftp命令使用。
    2013-07-07
  • postMessage消息通信Promise化的方法實現(xiàn)

    postMessage消息通信Promise化的方法實現(xiàn)

    postMessage Api 想必大家都不陌生,WebWorker 通信會用到,iframe 窗口之間通信也會用到,那么我們能不能將 postMessage 進(jìn)行一次轉(zhuǎn)化,把他變成類似 Promise 的使用方式,所以本文給大家介紹了postMessage消息通信Promise化的方法實現(xiàn),需要的朋友可以參考下
    2024-03-03
  • javascript實現(xiàn)tab切換的四種方法

    javascript實現(xiàn)tab切換的四種方法

    這篇文章主要為大家詳細(xì)介紹了javascript實現(xiàn)tab切換的四種方法,并且對每個方法進(jìn)行了評價,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2015-11-11
  • js使用for...of遍歷對象

    js使用for...of遍歷對象

    本文主要介紹了js使用for...of遍歷對象,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2026-05-05
  • js手機(jī)號4位顯示空格,銀行卡每4位顯示空格效果

    js手機(jī)號4位顯示空格,銀行卡每4位顯示空格效果

    這篇文章主要介紹了js手機(jī)號4位顯示空格,銀行卡每4位顯示空格效果,手機(jī)號和銀行卡號,按照每4位顯示一個空格的需求,非常具有實用價值,需要的朋友可以參考下。
    2017-03-03

最新評論

临安市| 廉江市| 都江堰市| 枝江市| 西林县| 延津县| 揭阳市| 漳浦县| 宁城县| 镇原县| 丽水市| 察隅县| 荃湾区| 内乡县| 贵定县| 大埔区| 镇坪县| 深泽县| 泊头市| 上杭县| 伊春市| 黑龙江省| 桃园县| 南通市| 响水县| 临邑县| 内黄县| 开化县| 鄂尔多斯市| 浮山县| 姜堰市| 邢台县| 北碚区| 贺兰县| 平远县| 冷水江市| 新余市| 苗栗市| 武川县| 肇州县| 怀远县|