JavaScript: JavaScript 日期
JavaScript 用 Date 对象处理日期和时间。它就像一块电子手表——能看当前时间,也能设定任意时刻,还能计算时间差。
1. Date对象的创建与操作
▶ 示例
JAVASCRIPT
// 本节代码示例
const message = "你好,世界!";
console.log(message);
这是最简单的示例,后续章节会详细解释。### (1) Date 对象创建
四种常见创建方式:
HTML
<script>
console.log(new Date()); // 当前时间
console.log(new Date("2025-06-19")); // 日期字符串
console.log(new Date(2025, 5, 19, 10, 30, 0)); // 年、月、日、时、分、秒
console.log(new Date(1718764800000)); // 时间戳(毫秒)
</script>
大坑预警:月份从 0 开始!0 = 一月,11 = 十二月。new Date(2025, 5, 19) 里的 5 是六月,不是五月。这是 Date 对象被吐槽最多的设计,没有之一。
(2) 获取日期时间
| 方法 | 返回 | 注意 |
|---|---|---|
getFullYear() |
4位年份 | 别用 getYear(),已废弃 |
getMonth() |
0-11 | 要 +1 才是实际月份 |
getDate() |
1-31 | 当月第几天 |
getDay() |
0-6 | 0=周日,不是周一! |
getHours() |
0-23 | — |
getMinutes() |
0-59 | — |
getSeconds() |
0-59 | — |
getDay() 返回的是星期几,不是当月第几天——要获取第几天用的是 getDate()。新手经常搞混。
(3) 设置日期时间
对应一组 set 方法:setFullYear()、setMonth()、setDate()、setHours()、setMinutes()、setSeconds()。设置时会自动进位:
HTML
<script>
const d = new Date(2025, 5, 19);
d.setDate(32); // 自动变成 7月2日
console.log(d.toLocaleDateString());
</script>
(4) 日期格式化
| 方法 | 示例输出 |
|---|---|
toLocaleDateString() |
"2025/6/19" |
toLocaleTimeString() |
"10:30:00" |
toLocaleString() |
"2025/6/19 10:30:00" |
这些方法会根据浏览器的语言环境自动格式化,中文浏览器显示中文格式。
(5) 时间戳和计算时间差
时间戳是自 1970年1月1日 00:00:00 UTC 起经过的毫秒数。
HTML
<script>
console.log(Date.now()); // 获取当前时间戳
console.log(new Date().getTime()); // 同上
</script>
计算时间差的核心思路:两个时间戳相减,得到毫秒差,再换算:
HTML
<script>
const start = Date.now();
for (let i = 0; i < 1000000; i++) {} // 模拟操作
const end = Date.now();
const diff = end - start; // 毫秒
const diffSeconds = diff / 1000; // 秒
console.log("耗时:" + diff + "ms(" + diffSeconds + "秒)");
</script>
▶ 示例:显示当前日期时间
HTML
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>当前日期时间</title>
<style>
body { font-family: sans-serif; padding: 20px; text-align: center; }
.clock { display: inline-block; padding: 24px 40px; background: #1a1a2e; color: #e0e0e0; border-radius: 12px; }
.time { font-size: 48px; font-weight: bold; color: #00d4ff; font-family: monospace; }
.date { font-size: 20px; margin-top: 8px; color: #a0a0c0; }
</style>
</head>
<body>
<h2>实时时钟</h2>
<div class="clock">
<div class="time" id="time">--:--:--</div>
<div class="date" id="date">----/--/--</div>
</div>
<script>
function updateClock() {
const now = new Date();
const h = String(now.getHours()).padStart(2, "0");
const m = String(now.getMinutes()).padStart(2, "0");
const s = String(now.getSeconds()).padStart(2, "0");
document.getElementById("time").textContent = `${h}:${m}:${s}`;
const y = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, "0");
const d = String(now.getDate()).padStart(2, "0");
const weekdays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
document.getElementById("date").textContent = `${y}年${month}月${d}日 ${weekdays[now.getDay()]}`;
}
updateClock();
setInterval(updateClock, 1000);
</script>
</body>
</html>
▶ 示例:日期信息详解
HTML
📖 仅展示
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>日期信息</title>
<style>
body { font-family: sans-serif; padding: 20px; }
table { border-collapse: collapse; margin: 16px 0; }
td, th { border: 1px solid #ddd; padding: 10px 16px; text-align: left; }
th { background: #4a90d9; color: #fff; }
.note { background: #fff8e1; padding: 12px; border-radius: 6px; border-left: 4px solid #f0ad4e; margin: 16px 0; }
</style>
</head>
<body>
<h2>Date 对象各方法返回值</h2>
<div id="output"></div>
<script>
const now = new Date();
const data = [
["getFullYear()", now.getFullYear(), "4位年份"],
["getMonth()", now.getMonth(), "0-11(需要+1)"],
["getDate()", now.getDate(), "1-31(当月第几天)"],
["getDay()", now.getDay(), "0-6(0=周日)"],
["getHours()", now.getHours(), "0-23"],
["getMinutes()", now.getMinutes(), "0-59"],
["getSeconds()", now.getSeconds(), "0-59"],
["getTime()", now.getTime(), "时间戳(毫秒)"],
];
document.getElementById("output").innerHTML = `
<table>
<tr><th>方法</th><th>返回值</th><th>说明</th></tr>
${data.map(r => `<tr><td><code>${r[0]}</code></td><td>${r[1]}</td><td>${r[2]}</td></tr>`).join("")}
</table>
<div class="note">
⚠️ <strong>月份从0开始</strong>:getMonth() 返回 ${now.getMonth()},实际月份是 ${now.getMonth()+1}月。
<strong>getDay() 是星期</strong>:返回 ${now.getDay()}(${["周日","周一","周二","周三","周四","周五","周六"][now.getDay()]}),不是日期!
</div>
`;
</script>
</body>
</html>
▶ 示例:倒计时计算
HTML
📖 仅展示
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>倒计时</title>
<style>
body { font-family: sans-serif; padding: 20px; text-align: center; }
.countdown { display: inline-block; padding: 24px; background: linear-gradient(135deg, #667eea, #764ba2); color: #fff; border-radius: 12px; margin: 16px 0; }
.countdown h3 { margin: 0 0 12px; font-size: 18px; }
.timer { display: flex; gap: 16px; justify-content: center; }
.unit { text-align: center; }
.number { font-size: 40px; font-weight: bold; font-family: monospace; }
.label { font-size: 12px; opacity: 0.8; }
.input-row { margin: 16px 0; }
input { padding: 8px 12px; font-size: 16px; border: 2px solid #ccc; border-radius: 6px; }
button { padding: 8px 20px; font-size: 16px; border: none; border-radius: 6px; cursor: pointer; background: #4a90d9; color: #fff; }
button:hover { background: #357abd; }
</style>
</head>
<body>
<h2>目标日期倒计时</h2>
<div class="input-row">
<input type="datetime-local" id="target" />
<button id="startBtn">开始倒计时</button>
</div>
<div class="countdown" id="countdown" style="display:none;">
<h3 id="targetLabel">距离目标还有</h3>
<div class="timer">
<div class="unit"><div class="number" id="days">0</div><div class="label">天</div></div>
<div class="unit"><div class="number" id="hours">0</div><div class="label">时</div></div>
<div class="unit"><div class="number" id="minutes">0</div><div class="label">分</div></div>
<div class="unit"><div class="number" id="seconds">0</div><div class="label">秒</div></div>
</div>
</div>
<script>
const defaultTarget = new Date();
defaultTarget.setDate(defaultTarget.getDate() + 7);
const dateStr = defaultTarget.toISOString().slice(0, 16);
document.getElementById("target").value = dateStr;
let timer = null;
document.getElementById("startBtn").addEventListener("click", function() {
const target = new Date(document.getElementById("target").value);
if (isNaN(target.getTime())) {
alert("请选择有效的日期时间");
return;
}
document.getElementById("countdown").style.display = "inline-block";
document.getElementById("targetLabel").textContent =
`距离 ${target.toLocaleString()} 还有`;
if (timer) clearInterval(timer);
function update() {
const now = Date.now();
const diff = target.getTime() - now;
if (diff <= 0) {
document.getElementById("days").textContent = "0";
document.getElementById("hours").textContent = "0";
document.getElementById("minutes").textContent = "0";
document.getElementById("seconds").textContent = "0";
document.getElementById("targetLabel").textContent = "时间到了!";
clearInterval(timer);
return;
}
const days = Math.floor(diff / (1000 * 60 * 60 * 24));
const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((diff % (1000 * 60)) / 1000);
document.getElementById("days").textContent = days;
document.getElementById("hours").textContent = String(hours).padStart(2, "0");
document.getElementById("minutes").textContent = String(minutes).padStart(2, "0");
document.getElementById("seconds").textContent = String(seconds).padStart(2, "0");
}
update();
timer = setInterval(update, 1000);
});
</script>
</body>
</html>
▶ 示例:时间差计算
HTML
📖 仅展示
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>时间差计算</title>
<style>
body { font-family: sans-serif; padding: 20px; }
.calc { max-width: 500px; margin: 16px auto; }
.row { margin: 12px 0; }
label { display: inline-block; width: 80px; font-weight: bold; }
input { padding: 8px 12px; font-size: 16px; border: 2px solid #ccc; border-radius: 6px; }
button { padding: 8px 20px; font-size: 16px; border: none; border-radius: 6px; cursor: pointer; background: #5cb85c; color: #fff; margin-top: 8px; }
button:hover { background: #449d44; }
.result { margin-top: 16px; padding: 16px; background: #f0f7ff; border-radius: 8px; border: 2px solid #4a90d9; }
.result div { margin: 4px 0; }
</style>
</head>
<body>
<h2 style="text-align:center;">时间差计算器</h2>
<div class="calc">
<div class="row">
<label>开始日期:</label>
<input type="date" id="start" />
</div>
<div class="row">
<label>结束日期:</label>
<input type="date" id="end" />
</div>
<div style="text-align:center;">
<button id="calcBtn">计算</button>
</div>
<div class="result" id="result" style="display:none;"></div>
</div>
<script>
const today = new Date();
const lastMonth = new Date();
lastMonth.setMonth(lastMonth.getMonth() - 1);
document.getElementById("start").value = lastMonth.toISOString().slice(0, 10);
document.getElementById("end").value = today.toISOString().slice(0, 10);
document.getElementById("calcBtn").addEventListener("click", function() {
const start = new Date(document.getElementById("start").value);
const end = new Date(document.getElementById("end").value);
if (isNaN(start.getTime()) || isNaN(end.getTime())) {
alert("请选择有效日期");
return;
}
const diffMs = Math.abs(end - start);
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
const diffMinutes = Math.floor(diffMs / (1000 * 60));
const diffWeeks = Math.floor(diffDays / 7);
document.getElementById("result").style.display = "block";
document.getElementById("result").innerHTML = `
<div><strong>相差天数:</strong>${diffDays} 天</div>
<div><strong>相差小时:</strong>${diffHours} 小时</div>
<div><strong>相差分钟:</strong>${diffMinutes} 分钟</div>
<div><strong>约合计:</strong>${diffWeeks} 周 ${diffDays % 7} 天</div>
`;
});
</script>
</body>
</html>
❓ 常见问题
Q 为什么
getMonth() 返回的月份要 +1?A 因为 Java 的
Date 类就是这么设计的,JavaScript 继承了这个"传统"。虽然所有人都觉得这设计很蠢,但改不了了——太多现有代码依赖这个行为。记住就好。Q
new Date("2025-06-19") 和 new Date(2025, 5, 19) 有区别吗?A 有。字符串解析的日期默认是 UTC 时间 0 点,而参数形式是本地时间。显示时可能差 8 小时(东八区)。如果只需要日期不关心时间,用参数形式更安全。
Q 如何计算"某人多少岁了"?
A 用当前年份减出生年份,然后检查今年生日是否已过:如果当前月份 < 出生月份,或者月份相同但日期 < 出生日期,年龄再减 1。
📖 小节
- 创建 Date 对象有多种方式:
new Date()、new Date(2024, 0, 1)、new Date("2024-01-01") - 获取日期时间用
getFullYear/getMonth/getDate/getDay/getHours/getMinutes/getSeconds - 设置日期时间用对应的
set方法,修改后原对象会改变 - 日期格式化:
toLocaleDateString本地化、toISOString标准格式、手动拼接 - 时间戳是毫秒数,
Date.now()获取当前时间戳,加减时间戳实现日期计算
📝 作业
- 编写一个函数
formatDate(date),返回"YYYY年MM月DD日 星期X"格式的字符串。注意月份和日期要补零。 - 编写一个函数
getAge(birthday),传入出生日期字符串(如"2000-03-15"),返回当前实足年龄。 - 编写一个"已过去多久"功能:输入一个过去的日期,显示"距今 X 年 X 月 X 天"或"X 天前"或"X 小时前"(根据时间远近自动选择格式)。