📅 JS Date 对象8大使用场景
new Date() 是JS最常用、最实用的内置对象,专门处理时间、日期!
基础获取、制定
// 获取当前时间
const now = new Date();
// 指定时间
const date = new Date("2025-10-01");
开发必用的 10 个实用方法
获取 年 / 月 / 日 / 时 / 分 / 秒
const date = new Date();
date.getFullYear(); // 年 → 2026
date.getMonth() + 1; // 月 → 3(注意:月份从0开始!必须+1)
date.getDate(); // 日 → 23
date.getHours(); // 时
date.getMinutes(); // 分
date.getSeconds(); // 秒
date.getDay(); // 星期 0=周日,1=周一 ... 6=周六
时间格式化
// 把 `2026-03-23T12:34:56.789Z` 变成 `2026-03-23 12:34:56`
function formatTime(date) {
const y = date.getFullYear();
const m = (date.getMonth() + 1).toString().padStart(2, '0');
const d = date.getDate().toString().padStart(2, '0');
const hh = date.getHours().toString().padStart(2, '0');
const mm = date.getMinutes().toString().padStart(2, '0');
const ss = date.getSeconds().toString().padStart(2, '0');
return `${y}-${m}-${d} ${hh}:${mm}:${ss}`;
}
获取时间戳
// 方式1
const ts = Date.now();
// 方式2
const ts2 = new Date().getTime();
console.log(ts); // 1742789012345
console.log(ts2); // 1742789012345
计算两个时间差
const start = new Date("2026-03-23").getTime();
const end = new Date("2026-03-25").getTime();
const diff = end - start; // 毫秒差
const day = diff / (1000 * 60 * 60 * 24); // 天数
倒计时功能
function countDown(endTime) {
const now = Date.now();
const diff = endTime - now;
const sec = diff / 1000;
const d = parseInt(sec / 3600 / 24);
const h = parseInt((sec / 3600) % 24);
const m = parseInt((sec / 60) % 60);
const s = parseInt(sec % 60);
return `${d}天 ${h}时 ${m}分 ${s}秒`;
}
判断是否是今天
function isToday(date) {
const today = new Date();
return date.getDate() === today.getDate()
&& date.getMonth() === today.getMonth()
&& date.getFullYear() === today.getFullYear();
}
时间转刚刚 / 几分钟前 / 几小时前
function timeAgo(timestamp) {
const now = Date.now();
const diff = (now - timestamp) / 1000;// /1000 ->转换为秒
if (diff < 60) return '刚刚';
if (diff < 3600) return parseInt(diff / 60) + '分钟前';
if (diff < 86400) return parseInt(diff / 3600) + '小时前';
return parseInt(diff / 86400) + '天前';
}
获取当月第一天 / 最后一天
// 当月第一天
const firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
// 当月最后一天
const lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);