简介
Day.js是一个轻量级的JavaScript库,用于解析,验证,操作和显示日期和时间。它提供了类似于Moment.js的API,但只有2kb大小,因此在加载和使用上比Moment.js更快。
安装和使用
你可以通过npm安装Day.js:
npm install dayjs
或者通过CDN引入:
<script src="https://cdn.jsdelivr.net/npm/dayjs"></script>
使用时,你可以像这样创建一个Day.js对象:
const dayjs = require('dayjs') const today = dayjs()
API
Day.js提供了许多方法来操作和显示日期和时间。下面列出了一些最常用的API:
获取当前时间
const now = dayjs() // 获取当前时间
格式化时间
const date = dayjs('2023-04-07') date.format('YYYY-MM-DD') // '2023-04-07'
添加/减少时间
const date = dayjs('2023-04-07') date.add(1, 'year') // 添加1年,返回Day.js对象 date.subtract(1, 'month') // 减少1个月,返回Day.js对象
比较时间
const date1 = dayjs('2023-04-07') const date2 = dayjs('2024-05-08') date1.isBefore(date2) // true date1.isAfter(date2) // false
时间差
const date1 = dayjs('2023-04-07') const date2 = dayjs('2024-05-08') date2.diff(date1, 'months') // 13
更多API和用法请查看官方文档。
示例代码
下面是一些Day.js的示例代码:
-- -------------------- ---- ------- -- ------------ ----- --- - ------- ---------------------------------- ----------- -- ------------ ----- ----- - ------------------- ----- ----- - ------------------- ----- -------- - ----------------- ------- --------------------- -- ------- ----- ---------- - -------------------------------- -----------------------展开代码
总结
Day.js是一个功能全面、代码精简、速度快的时间处理库。它提供了类似于Moment.js的API,但只有2kb大小,因此可以帮助你更快地加载和使用时间处理功能。如果你需要在项目中处理时间,建议尝试使用Day.js。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/31562