Moment.js 是一个流行的 JavaScript 日期和时间处理库,用于解析、验证、操作和显示日期和时间。以下是一个关于 Moment.js 的基本用法示例:
1. 安装:
npm install moment
2. 导入:在需要使用 Moment.js 的地方,导入 Moment.js 模块。
import moment from "moment";
3. 解析日期和时间:使用 `moment()` 函数传入日期和时间字符串或 JavaScript Date 对象来创建 Moment 对象。
const now = moment(); // 当前时间
const specificDate = moment('2022-01-01'); // 解析特定日期
4. 格式化日期和时间:使用 `format()` 方法将 Moment 对象格式化为指定的日期和时间字符串。
const formattedDate = now.format('YYYY-MM-DD'); // 格式化为 '2023-09-14'
const formattedTime = now.format('HH:mm:ss'); // 格式化为 '23:59:59'
const formattedDateTime = now.format('YYYY-MM-DD HH:mm:ss'); // 格式化为 '2023-09-14 23:59:59'
5. 操作日期和时间:使用 Moment.js 提供的方法对 Moment 对象进行日期和时间操作。
const tomorrow = now.add(1, 'day'); // 加一天
const nextHour = now.add(1, 'hour'); // 加一小时
const twoMonthsAgo = now.subtract(2, 'months'); // 减去两个月
6. 显示相对时间:使用 `fromNow()` 方法显示相对于当前时间的相对时间表达。
const relativeTime = specificDate.fromNow(); // '9 months ago'
7. 多语言支持:Moment.js 支持多语言化,可以设置不同语言环境以正确显示日期和时间的本地化格式。
moment.locale('zh-cn'); // 设置为中文环境
const localizedDate = now.format('LL'); // 格式化为中文日期格式,如 '2023年9月14日'
注:自 2020 年 9 月开始,Moment.js 停止维护。