[特殊字符] JS Date 对象8大使用场景

📅 JS Date 对象8大使用场景

new Date() 是JS最常用、最实用的内置对象,专门处理时间、日期

基础获取、制定

js 复制代码
// 获取当前时间
const now = new Date();

// 指定时间
const date = new Date("2025-10-01");

开发必用的 10 个实用方法

获取 年 / 月 / 日 / 时 / 分 / 秒

js 复制代码
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=周六

时间格式化

js 复制代码
// 把 `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}`;
}

获取时间戳

js 复制代码
// 方式1
const ts = Date.now();

// 方式2
const ts2 = new Date().getTime();

console.log(ts); // 1742789012345
console.log(ts2); // 1742789012345

计算两个时间差

js 复制代码
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); // 天数

倒计时功能

js 复制代码
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}秒`;
}

判断是否是今天

js 复制代码
function isToday(date) {
  const today = new Date();
  return date.getDate() === today.getDate()
      && date.getMonth() === today.getMonth()
      && date.getFullYear() === today.getFullYear();
}

时间转刚刚 / 几分钟前 / 几小时前

js 复制代码
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) + '天前';
}

获取当月第一天 / 最后一天

js 复制代码
// 当月第一天
const firstDay = new Date(date.getFullYear(), date.getMonth(), 1);

// 当月最后一天
const lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
相关推荐
IT_陈寒1 小时前
React的useState居然还有这种坑?我差点删库跑路
前端·人工智能·后端
Pedantic2 小时前
SwiftUI 手势笔记
前端·后端
橙子家3 小时前
浏览器缓存之【结构化数据库与缓存】: IndexedDB、Cache storage 和 Storage buckets
前端
user20585561518133 小时前
X6 中边悬浮置顶,规避 `mouseleave` 事件丢失问题
前端
李明卫杭州3 小时前
CSS aspect-ratio 属性完全指南
前端
Pedantic5 小时前
SwiftUI 手势层级(Gesture Hierarchy)详解
前端
飘尘5 小时前
前端转型全栈(Java后端)的快速上手指引
前端·后端·全栈
一颗烂土豆5 小时前
Meshopt 压缩深度解析,为什么它比 Draco 更快
前端·javascript·webgl
浏览器工程师6 小时前
AI Agent 接浏览器任务,先别让它一路点到底
前端·后端