在JavaScript开发中,处理日期和时间常常让人头大。过去我们多依赖 Moment.js,但随着ES模块与新项目对性能的苛刻要求,Day.js以"极简API、2k体积、与Moment高度兼容"成为新宠。本文带你从入门到实战,系统掌握Day.js!
1. 安装与入门
安装
Node.js
使用npm:
bash
npm install dayjs
Browser
使用cdn:
html
<!-- CDN example (jsDelivr) --> <script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script> <script>dayjs().format()</script>
快速体验
js
const dayjs = require('dayjs'); // Node环境
console.log(dayjs().format()); //当前时间 例如: 2025-05-30T09:55:02+08:00
2. Day.js的基本用法
2.1 创建日期对象
js
dayjs(); // 当前时间
dayjs('2024-06-01'); // 指定日期
dayjs('2024-06-01 12:00', 'YYYY-MM-DD HH:mm'); // 指定格式
dayjs(1716816000000); // 时间戳(毫秒)
2.2 格式化日期
js
dayjs().format('YYYY-MM-DD HH:mm:ss'); // 2025-05-30T09:55:02+08:00
dayjs('2024-06-01').format('dddd'); // Saturday
2.3 取日期各项
js
dayjs().year(); // 2024
dayjs().month(); // 0~11,0为1月
dayjs().date(); // 几号
dayjs().hour(); // 小时
dayjs().minute(); // 分
dayjs().second(); // 秒
dayjs().day(); // 星期几(0=周日)
3. 日期计算
3.1 加减时间
js
dayjs().add(7, 'day').format('YYYY-MM-DD'); // 加7天
dayjs().subtract(1, 'month').format('YYYY-MM'); // 减1月
3.2 日期差值
js
const start = dayjs('2024-06-01');
const end = dayjs('2024-06-20');
end.diff(start, 'day'); // 19
end.diff(start, 'month'); // 0
支持单位: 'year', 'month', 'week', 'day', 'hour', 'minute', 'second'
3.3 判断日期
js
const d1 = dayjs('2024-06-01');
const d2 = dayjs('2024-07-01');
d1.isBefore(d2); // true
d1.isAfter(d2); // false
d1.isSame('2024-06-01', 'day'); // true
4. 进阶玩法------解析与插件系统
Day.js核心功能"够用即止",更多高级需求需"插件"支持。
4.1 本地化(多语言)
js
const dayjs = require('dayjs');
const localizedFormat = require('dayjs/plugin/localizedFormat');
const localeLan = require('dayjs/locale/zh-cn');
dayjs.extend(localizedFormat); // 加载本地化格式插件
dayjs.locale(localeLan); // 使用中文
console.log(dayjs().format('LLLL')); // 2025年5月30日星期五上午10点27分
format
格式可以参考day.js.org/docs/zh-CN/...
4.2 定制解析与显示
- 自定义格式解析:
js
const customParseFormat = require('dayjs/plugin/customParseFormat');
dayjs.extend(customParseFormat);
const d = dayjs('2024年06月01日', 'YYYY年MM月DD日');
console.log(d.format('YYYY-MM-DD')); // 2024-06-01
4.3 时间区间(isBetween)
js
const isBetween = require('dayjs/plugin/isBetween');
dayjs.extend(isBetween);
let now = dayjs('2024-06-10');
console.log(now.isBetween('2024-06-01', '2024-06-20')); // true
4.4 相对时间(fromNow)
js
const dayjs = require('dayjs');
const localizedFormat = require('dayjs/plugin/localizedFormat');
const localeLan = require('dayjs/locale/zh-cn');
const relativeTime = require('dayjs/plugin/relativeTime');
dayjs.extend(localizedFormat); // 加载本地化格式插件
dayjs.locale(localeLan); // 使用中文
dayjs.extend(relativeTime);
console.log(dayjs().subtract(1, 'day').fromNow()); // "1天前"
console.log(dayjs().add(2, 'hour').fromNow()); // "2小时内"
5. 总结
- 体积小、API现代、用法极像Moment、扩展性极佳。
- 适合前端/Node后端所有涉及时钟、日期、倒计时、提醒等场景。
- 更多高级玩法推荐直接查看 官方插件列表
点个赞,关注我获取更多实用 JavaScript 技术干货!如果觉得有用,记得收藏本文!