[特殊字符] 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);
相关推荐
萧瑟余晖1 分钟前
Java深入解析篇十八之响应式编程
java·开发语言
看浪的路人5 分钟前
第5讲:代码审查与 Bug 检测
开发语言·windows·python
netccdn8 分钟前
Hough变换检测直线(Matlab)
开发语言·计算机视觉·matlab
有点。13 分钟前
C++深度优先搜索(三)
开发语言·c++·深度优先
天空'之城15 分钟前
C 语言工业级通用组件手写 25:简易日志系统
c语言·开发语言·日志系统·嵌入式调试·调试打印
程序喵大人27 分钟前
【C++进阶】STL算法与函数对象 -【C++进阶】STL算法与函数对象
开发语言·c++·算法
逍遥德34 分钟前
ECMAScript 各个版本的语法列表
前端·javascript·ecmascript·es6
用户0595401744637 分钟前
把AI聊天机器人记忆存储测试从3小时压到5分钟,我用Pytest + Docker搭了一套自动化回归
前端·css
明月_清风38 分钟前
显存即正义:不同显存容量能训多大的模型?一文说清硬件边界与训练策略
前端·后端·ai编程
weixin_BYSJ198739 分钟前
【java项目分享】springboot阅读推荐平台10600
java·javascript·spring boot·python·django·flask·php