[特殊字符] 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);
相关推荐
GreenTea17 分钟前
从 Claw-Code 看 AI 驱动的大型项目开发:2 人 + 10 个自治 Agent 如何产出 48K 行 Rust 代码
前端·人工智能·后端
渣渣xiong1 小时前
从零开始:前端转型AI agent直到就业第五天-第十一天
前端·人工智能
布局呆星1 小时前
Vue3 | 组件通信学习小结
前端·vue.js
C澒1 小时前
IntelliPro 企业级产研协作平台:前端智能生产模块设计与落地
前端·ai编程
wjs20242 小时前
JavaScript 语句
开发语言
OpenTiny社区2 小时前
重磅预告|OpenTiny 亮相 QCon 北京,共话生成式 UI 最新技术思考
前端·开源·ai编程
前端老实人灬2 小时前
web前端面试题
前端
Moment3 小时前
AI 全栈指南:NestJs 中的 Service Provider 和 Module
前端·后端·面试