使用JavaScript獲取當(dāng)前日期時(shí)間及其它操作
在 JavaScript 中,處理“當(dāng)前日期和時(shí)間”是非常常見(jiàn)的需求,通常通過(guò) Date 對(duì)象實(shí)現(xiàn)。以下是你可能會(huì)用到的典型操作合集,涵蓋當(dāng)前時(shí)間獲取、格式化、加減時(shí)間、比較、時(shí)間戳轉(zhuǎn)換等。
1. 獲取當(dāng)前日期時(shí)間
const now = new Date(); console.log(now); // 示例:2025-08-03T09:41:20.123Z
2. 獲取年/月/日/小時(shí)/分鐘/秒
const now = new Date();
const year = now.getFullYear(); // 年
const month = now.getMonth() + 1; // 月(注意:從 0 開(kāi)始,所以要 +1)
const date = now.getDate(); // 日
const hour = now.getHours(); // 小時(shí)
const minute = now.getMinutes(); // 分鐘
const second = now.getSeconds(); // 秒
console.log(`${year}-${month}-${date} ${hour}:${minute}:${second}`);
3. 獲取當(dāng)前時(shí)間戳
const timestamp = Date.now(); // 毫秒數(shù) console.log(timestamp); // 示例:1754262080123
4. 時(shí)間加減操作(如當(dāng)前時(shí)間+1天)
const now = new Date(); const tomorrow = new Date(now.getTime() + 24 * 60 * 60 * 1000); // 加一天 console.log(tomorrow.toString());
你也可以加小時(shí)、分鐘等:
// 加2小時(shí) const twoHoursLater = new Date(now.getTime() + 2 * 60 * 60 * 1000);
5. 時(shí)間格式化函數(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. 時(shí)間戳轉(zhuǎn)日期
const date = new Date(1754262080123); console.log(date.toLocaleString()); // 根據(jù)本地格式顯示
7. 日期字符串轉(zhuǎn)時(shí)間戳
const timestamp = new Date("2025-08-03 18:30:00").getTime();
console.log(timestamp); // 輸出對(duì)應(yīng)時(shí)間戳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(更簡(jiǎn)潔)
安裝dayjs(推薦輕量庫(kù))
npm install dayjs
示例
import dayjs from 'dayjs';
console.log(dayjs().format('YYYY-MM-DD HH:mm:ss')); // 當(dāng)前時(shí)間
console.log(dayjs().add(1, 'day').format()); // 明天
console.log(dayjs('2025-08-01').isBefore('2025-08-03')); // true
好的,下面是一個(gè)瀏覽器可直接運(yùn)行的 HTML 頁(yè)面,內(nèi)含完整的 JS 腳本,你只需復(fù)制以下代碼到本地 .html文件中打開(kāi)即可查看效果,或直接在瀏覽器開(kāi)發(fā)者工具中運(yùn)行 JS。
完整示例:獲取當(dāng)前時(shí)間、格式化、加減、比較、時(shí)間戳等
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JS 時(shí)間操作演示</title>
</head>
<body>
<h2>JavaScript 時(shí)間處理 Demo</h2>
<pre id="output"></pre>
<script>
const output = [];
// 1. 當(dāng)前時(shí)間
const now = new Date();
output.push("當(dāng)前時(shí)間對(duì)象: " + now);
// 2. 分解日期
output.push("年: " + now.getFullYear());
output.push("月: " + (now.getMonth() + 1));
output.push("日: " + now.getDate());
output.push("時(shí): " + now.getHours());
output.push("分: " + now.getMinutes());
output.push("秒: " + now.getSeconds());
// 3. 時(shí)間戳
const timestamp = Date.now();
output.push("當(dāng)前時(shí)間戳: " + 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("格式化時(shí)間: " + formatDate(now));
// 5. 時(shí)間加一天
const tomorrow = new Date(now.getTime() + 24 * 60 * 60 * 1000);
output.push("明天同一時(shí)間: " + formatDate(tomorrow));
// 6. 比較兩個(gè)日期
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. 時(shí)間戳轉(zhuǎn)日期
const tsToDate = new Date(1754262080123);
output.push("從時(shí)間戳生成時(shí)間: " + formatDate(tsToDate));
// 8. 字符串轉(zhuǎn)時(shí)間戳
const strToTs = new Date("2025-08-03 20:00:00").getTime();
output.push("字符串轉(zhuǎn)時(shí)間戳: " + strToTs);
// 顯示在頁(yè)面上
document.getElementById('output').textContent = output.join('\n');
</script>
</body>
</html>
功能亮點(diǎn)
- 獲取當(dāng)前時(shí)間(原始和格式化)
- 顯示年、月、日、時(shí)、分、秒
- 獲取當(dāng)前時(shí)間戳
- 時(shí)間加一天
- 時(shí)間戳<->日期互轉(zhuǎn)
- 日期比較
如果你還需要實(shí)現(xiàn):
- 定時(shí)器(
setInterval實(shí)時(shí)更新時(shí)間) - 倒計(jì)時(shí)或時(shí)間差計(jì)算
- 使用 Day.js 或 Moment.js 美化
我可以在這個(gè) Demo 基礎(chǔ)上擴(kuò)展一個(gè)小“時(shí)間工具頁(yè)面”。是否需要?
下面是一個(gè)可在瀏覽器直接打開(kāi)的完整時(shí)間工具頁(yè)面,包含以下功能:
功能列表
- 實(shí)時(shí)顯示當(dāng)前時(shí)間(每秒更新)
- 時(shí)間戳<->日期字符串互轉(zhuǎn)
- 計(jì)算兩個(gè)日期之間的時(shí)間差(天數(shù))
- 日期加減工具(+/- 天數(shù))
- 所有結(jié)果動(dòng)態(tài)顯示
一鍵復(fù)制以下 HTML 保存為time-tools.html即可運(yùn)行:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>JavaScript 時(shí)間工具</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 時(shí)間工具合集</h1>
<div class="section">
<h2> 實(shí)時(shí)當(dāng)前時(shí)間</h2>
<div class="output" id="clock">加載中...</div>
</div>
<div class="section">
<h2> 時(shí)間戳 ?? 日期字符串</h2>
<div>
<label>時(shí)間戳 ? 日期:</label>
<input type="number" id="tsInput" placeholder="如 1754262080123">
<button onclick="convertToDate()">轉(zhuǎn)換</button>
<div class="output" id="tsToDateOut"></div>
</div>
<div>
<label>日期 ? 時(shí)間戳:</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> 兩個(gè)日期之間相差幾天</h2>
<input type="date" id="diffStart"> ?
<input type="date" id="diffEnd">
<button onclick="calcDiff()">計(jì)算</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()">計(jì)算</button>
<div class="output" id="addResult"></div>
</div>
<script>
// 1. 實(shí)時(shí)時(shí)鐘
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. 時(shí)間戳轉(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)時(shí)間戳
function convertToTs() {
const dateStr = document.getElementById('dateInput').value;
const date = new Date(dateStr);
if (isNaN(date.getTime())) {
document.getElementById('dateToTsOut').textContent = " 日期格式無(wú)效";
} else {
document.getElementById('dateToTsOut').textContent = date.getTime();
}
}
// 3. 計(jì)算日期差
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 = " 請(qǐng)選擇兩個(gè)有效日期";
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 = " 起始日期無(wú)效";
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
雙擊打開(kāi)瀏覽器
即可使用所有時(shí)間工具,無(wú)需聯(lián)網(wǎng),無(wú)依賴(lài)
到此這篇關(guān)于使用JavaScript獲取當(dāng)前日期時(shí)間及其它操作的文章就介紹到這了,更多相關(guān)JavaScript獲取當(dāng)前日期時(shí)間內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
由document.body和document.documentElement想到的
不知道大家對(duì)這個(gè)標(biāo)題有沒(méi)有想法,反正此前我一直把他們混為了一談。其實(shí)不然,首先需有個(gè)“標(biāo)準(zhǔn)”的概念。2009-04-04
postMessage消息通信Promise化的方法實(shí)現(xiàn)
postMessage Api 想必大家都不陌生,WebWorker 通信會(huì)用到,iframe 窗口之間通信也會(huì)用到,那么我們能不能將 postMessage 進(jìn)行一次轉(zhuǎn)化,把他變成類(lèi)似 Promise 的使用方式,所以本文給大家介紹了postMessage消息通信Promise化的方法實(shí)現(xiàn),需要的朋友可以參考下2024-03-03
javascript實(shí)現(xiàn)tab切換的四種方法
這篇文章主要為大家詳細(xì)介紹了javascript實(shí)現(xiàn)tab切換的四種方法,并且對(duì)每個(gè)方法進(jìn)行了評(píng)價(jià),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2015-11-11
js手機(jī)號(hào)4位顯示空格,銀行卡每4位顯示空格效果
這篇文章主要介紹了js手機(jī)號(hào)4位顯示空格,銀行卡每4位顯示空格效果,手機(jī)號(hào)和銀行卡號(hào),按照每4位顯示一個(gè)空格的需求,非常具有實(shí)用價(jià)值,需要的朋友可以參考下。2017-03-03

