S05-04 Library-Day.js
[TOC]
概述
Day.js
Day.js:是一个轻量级、功能强大、且与 Moment.js 的 API 高度兼容的 JS 库,用于解析、验证、操作和显示日期和时间。
核心特点:
极其轻量: Day.js 的核心库体积非常小,只有大约 2KB(经过 Gzip 压缩)。这意味着引入它对您的项目性能影响微乎其微。
与 Moment.js API 高度兼容: 如果你熟悉 Moment.js,那么使用 Day.js 几乎不需要学习成本。绝大多数 Moment.js 的 API 在 Day.js 中都以相同的方式工作,这使得从 Moment.js 迁移到 Day.js 非常容易。
不可变: Day.js 对象是不可变的。所有操作(如增加时间、设置单位等)都会返回一个新的 Day.js 实例,而不会改变原始对象。这有助于避免在复杂应用中因意外修改而导致的 bug。
jsconst date1 = dayjs('2023-10-01'); const date2 = date1.add(1, 'day'); console.log(date1.format()); // 仍然是 ‘2023-10-01’ console.log(date2.format()); // 新的对象 ‘2023-10-02’
插件系统: 核心库只包含最常用的功能。如果你需要更高级的功能(如时区支持、相对时间、日历显示等),可以通过官方插件灵活地扩展。这保证了核心的简洁,同时又能满足复杂的需求。
国际化支持: 通过插件,Day.js 可以轻松支持多种语言和地区设置,让你的应用能够以本地化的格式显示日期和时间。
对比 Moment.js
对比 Moment.js:
- 支持 Tree-Shaking:不同于 Moment.js,Day.js 支持 Tree-Shaking 算法。
- API 兼容:Moment.js 和 Day.js 的 API 基本相同,学习成本低。
- 更加轻量:Day.js 由于采用了 Tree-Shaking 算法,导致它的文件体积大幅缩小,只有 2KB。而 Moment.js 文件体积有 67+KB 大小。
- 更好的国际化支持:Day.js 国际化采用手动加载方式;而 Moment.js 国际化文件会很大。
基本使用
安装
方式一:CDN
sh# jsdelivr https://cdn.jsdelivr.net/npm/dayjs/dayjs.min.js # bootcdn https://cdn.bootcdn.net/ajax/libs/dayjs/1.11.18/dayjs.min.js
方式二:下载源码,本地引入
html<script src="https://cdn.jsdelivr.net/npm/dayjs/dayjs.min.js"></script> <script> dayjs().format() </script>
基本使用
示例:获取/设置时间:
常用方法
工厂函数
dayjs():
(|timestamp|dayStr|Date)
,工厂函数,返回一个包含日期和时间的 Day.js 对象。dayjs():
()
,无参数js// 参数为空,返回当前时间和日期 var now = dayjs()
dayjs():
(timestamp)
,时间戳参数(毫秒)jsvar day = dayjs(1656206934331)
dayjs.unix():
(timestamp)
,时间戳参数(秒)jsvar day = dayjs.unix(1318781876)
dayjs():
(dayStr)
,日期字符串参数传入ISO 8601 格式时间字符串,会解析该时间字符串
jsdayjs('2018-04-04T16:00:00.000Z') // ISO 8601 格式
依赖第三方插件,可以解析其他格式的时间字符串
jsdayjs.extend(customParseFormat) dayjs("12-25-1995", "MM-DD-YYYY")
如果想解析包含本地化语言的日期字符串,可以传入第三个参数。
jsrequire('dayjs/locale/zh-cn') dayjs('2018 三月 15', 'YYYY MMMM DD', 'zh-cn')
最后一个参数可传入布尔值来启用严格解析模式。 严格解析要求格式和输入内容完全匹配,包括分隔符。
jsdayjs('1970-00-00', 'YYYY-MM-DD').isValid() // true dayjs('1970-00-00', 'YYYY-MM-DD', true).isValid() // false dayjs('1970-00-00', 'YYYY-MM-DD', 'es', true).isValid() // false
如果您不知道输入字符串的确切格式,但知道它可能是几种中的一种,可以使用数组传入多个格式。
jsdayjs("12-25-2001", ["YYYY", "YYYY-MM-DD"], 'es', true);
dayjs():
(Date)
,日期对象参数jsvar day = dayjs(new Date('2025-9-29'))
dayjs 函数:
Day.js 对象:
显示时间
day.format():
(formatStr)
,根据传入的占位符返回格式化后的日期。js// 默认返回的是 ISO8601 格式字符串 '2020-04-02T08:02:17-05:00' dayjs().format() // 将字符放在方括号中,即可原样返回而不被格式化替换 (例如, [MM])。 dayjs('2019-01-25').format('[YYYYescape] YYYY-MM-DDTHH:mm:ssZ[Z]') // 'YYYYescape 2019-01-25T00:00:00-02:00Z' dayjs('2019-01-25').format('DD/MM/YYYY') // '25/01/2019'
获取/设置时间
- day.year():
(num?)
,获取或设置年份。 - day.month():
(num?)
,获取或设置月份。月份是从 0 开始计算的,即 1 月是 0。 - day.date():
(num?)
,获取或设置月份里的日期。 - day.hour():
(num?)
,获取或设置小时。 - day.minute():
(num?)
,获取或设置分钟。 - day.second():
(num?)
,获取或设置秒。 - day.millisecond():
(num?)
,获取或设置毫秒。
示例:获取/设置时间:
操作时间
day.add():
(num, unit)
,返回增加一定时间的复制的 Day.js 对象。jsdayjs().add(1, 'year') // 增加一年 dayjs().add(-1, 'year') // num 支持负数
day.subtract():
(num, unit)
,返回减去一定时间的复制的 Day.js 对象。jsdayjs().subtract(7, 'year') // 减去7年
day.startOf():
(unit)
,返回复制的 Day.js 对象,并设置到一个时间的开始。jsdayjs().startOf('year') // 获取一年的开始,如 2025-01-01 00:00:00
day.endOf():
(unit)
,返回复制的 Day.js 对象,并设置到一个时间的末尾。jsdayjs().endOf('month') // 获取一月的结束,如 2025-09-30 23:59:59
unit 参数支持的单位列表:
单位 | 缩写 | 描述 |
---|---|---|
year | y | 年 |
month | M | 月份(0-11) |
day | d | 日 |
hour | h | 小时 |
minute | m | 分钟 |
second | s | 秒 |
millisecond | ms | 毫秒 |
week | w | 周 |
quarter | Q | 季度,依赖 QuarterOfYear 插件 |
插件
基本使用
- dayjs.extend():
(plugin, options?)
,用于加载插件以增强库的功能。
示例:插件的基本使用
常用插件
relativeTime
- day.fromNow():
(withoutSuffix?)
,返回 str 距离现在的相对时间。 - day.toNow():
(withoutSuffix?)
,返回 str 到现在的相对时间。 - day.from():
(compared, withoutSuffix?)
,返回 str 距离 X 的相对时间。 - day.to():
(compared, withoutSuffix?)
,返回 str 到 X 的相对时间。
示例:relativeTime
<script src="https://cdn.jsdelivr.net/npm/dayjs@1.11.18/plugin/relativeTime.js"></script>
<script>
dayjs.extend(relativeTime)
// from()
dayjs().from(dayjs('1990-01-01')) // 31 年后
dayjs().from(dayjs('1990-01-01'), true) // 31 年
// fromNow()
dayjs().fromNow()
// to()
dayjs().to(dayjs('1990-01-01')) // 31 年前
// toNow()
dayjs().toNow()
</script>
国际化
基本使用
.locale():
(localeName?,obj?,isLocal?)
,用于设置或获取当前使用的语言环境。dayjs.locale():
()
,获取当前语言环境。jsconst currentLocale = dayjs.locale(); // "en"(默认)
dayjs.locale():
(localeName?, obj?, isLocal?)
,全局设置语言环境。jsconst result = dayjs.locale('zh-cn'); console.log(result); // "zh-cn"
day.locale():
(localeName?)
,实例方法设置语言环境。jsconst instance = dayjs().locale('zh-cn'); console.log(instance.locale()); // "zh-cn"
localeName 常用值:
'en'
- 英语(默认)'zh-cn'
- 简体中文'zh-tw'
- 繁体中文'ja'
- 日语'ko'
- 韩语'fr'
- 法语'de'
- 德语'es'
- 西班牙语'ru'
- 俄语
示例:全局语言环境设置
<script src="https://cdn.jsdelivr.net/npm/dayjs/dayjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dayjs@1.11.18/locale/zh-cn.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dayjs@1.11.18/locale/ja.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dayjs@1.11.18/locale/fr.js"></script>
<script>
// 1. 获取当前语言环境
console.log(dayjs.locale()); // "en"(默认)
// 2. 设置全局语言环境为中文
dayjs.locale('zh-cn');
console.log(dayjs.locale()); // "zh-cn"
// 3. 使用新语言环境格式化日期
console.log(dayjs().format('LLLL'));
// 输出:"2023年10月26日星期四 15:30"
// 切换到日语
dayjs.locale('ja');
console.log(dayjs().format('LLLL'));
// 输出:"2023年10月26日 木曜日 15:30"
</script>
示例:实例级别语言环境设置
// 全局设置为中文
dayjs.locale('zh-cn');
const date = dayjs('2023-12-25');
// 创建使用不同语言的实例
const chineseDate = date.locale('zh-cn');
const japaneseDate = date.locale('ja');
const englishDate = date.locale('en'); // 切换回英语
console.log(chineseDate.format('LLLL'));
// "2023年12月25日星期一 00:00"
console.log(japaneseDate.format('LLLL'));
// "2023年12月25日 月曜日 00:00"
console.log(englishDate.format('LLLL'));
// "Monday, December 25, 2023 12:00 AM"
// 原始实例不受影响
console.log(date.format('LLLL'));
// 仍然使用全局中文设置
示例:自定义语言环境
// 创建自定义语言环境
const customLocale = {
name: 'zh-custom',
months: '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'),
monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),
weekdays: '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'),
weekdaysShort: '周日_周一_周二_周三_周四_周五_周六'.split('_'),
weekdaysMin: '日_一_二_三_四_五_六'.split('_'),
formats: {
LT: 'HH:mm',
LTS: 'HH:mm:ss',
L: 'YYYY/MM/DD',
LL: 'YYYY年M月D日',
LLL: 'YYYY年M月D日Ah点mm分',
LLLL: 'YYYY年M月D日ddddAh点mm分'
},
relativeTime: {
future: '%s后',
past: '%s前',
s: '几秒',
m: '1分钟',
mm: '%d分钟',
h: '1小时',
hh: '%d小时',
d: '1天',
dd: '%d天',
M: '1个月',
MM: '%d个月',
y: '1年',
yy: '%d年'
}
};
// 注册自定义语言环境
dayjs.locale(customLocale, null, true);
// 使用自定义语言环境
console.log(dayjs().format('LLLL'));
console.log(dayjs().add(1, 'day').fromNow());
手写 Day.js
基本实现
1、返回 Dayjs 对象
2、添加原型方法
3、兼容 Node 环境:判断 globalThis
是否存在:
- 如果存在,使用
globalThis
- 如果不存在,使用
g
- 如果都不存在,使用
self