Moment.js 常用方法总结及常见错误

1,360 阅读3分钟

“我正在参加「掘金·启航计划」”

Moment.js 是一个轻量级的 JavaScript 时间库,可以非常方便的处理时间格式问题,总结了一些常用的方法,方便快速查找。

Moment 对象

// moment 对象
moment();
// moment 对象转化为原生 JS 对象
moment().toDate();
// 转化为年月日时分秒
moment().toArray();
moment().toObject();

格式化

// 获取格式化后的时间
moment().format('YYYY-MM-DD HH:mm:ss');
moment().format('YYYY年MM月DD日');

几天前几天后

// 几天前或几天后的时间
// 对应的有 years, months, days, weeks, hours, minutes, seconds,例如:
// 3 天后的时间
moment().add(3, 'days').format('YYYY-MM-DD');
// 7 天前的时间
moment().subtract(7, 'days').format('YYYY-MM-DD');
// 注意这样的写法月份是从 0 开始的,0 代表 1 月,11 代表 12 月
moment([2022, 0, 1]).fromNow(); // 8个月前

时间戳

// 获取时间戳,以秒为单位
// 返回值为字符串类型
moment().format('X');
// 获取时间戳,以秒为单位
// 返回值为数值型
moment().unix();
// 获取时间戳,以毫秒为单位
// 返回值为字符串类型
moment().format('x');
// 获取时间戳,以毫秒为单位
// 返回值为数值型
moment().valueOf();

起止时间 00:00:00

// 获取当天 00:00:00 时刻,返回 moment 对象
// startOf 对应的有 endOf
moment().startOf('day');
// 格式化示例:moment().startOf('month').format('YYYY-MM-DD HH:mm:ss')
// 2020-08-01 00:00:00
// 获取本周周一 00:00:00 时刻,返回 moment 对象
moment().startOf('isoWeek');
// 获取本月第一天 00:00:00 时刻,返回 moment 对象
moment().startOf('month');

获取设置年月日时分秒

// 获取当前年
moment().year();
moment().get('year');
// 对于年月日时分秒,均有对应的 set 方法,用于设置值,例如:
moment().year(2022);
moment().set('year', 2022);
// 获取当前月,0 ~ 11,比实际月份少 1
moment().month();
moment().get('month');
// 获取当月当天
moment().date();
moment().get('date');
// 获取星期几
// day, weekday 结果为 0 ~ 6,0:周日,6:周六
// isoWeekday 结果为 1 ~ 7,1:周一,7:周日
moment().day();
moment().weekday();
moment().isoWeekday();
moment().get('day');
moment().get('weekday');
moment().get('isoWeekday');
// 获取小时
moment().hours();
moment().get('hours');
// 获取分钟
moment().minutes();
moment().get('minutes');
// 获取秒
moment().seconds();
moment().get('seconds');

时间差

// 时间差
const startTime = moment();
const endTime = moment().add(7, 'days');
// 获取毫秒数
endTime.diff(startTime);
// 获取相差天数
// 同理,第二个参数还可以为 years, months, days, weeks, minutes, seconds
endTime.diff(startTime, 'days');

获取某年的最后一天

//日期可以是年的格式 或者 年月的格式 也可以是年月日的格式
moment(日期).endOf('year').format("YYYY-MM-DD")

momentjs 获取两个日期相隔天数

moment('2020-11-21').diff(moment('2020-11-01'), 'days')
// 20

其它

// 获取当月天数
moment().daysInMonth();
// 获取当前年的周数
moment().weeksInYear();
// 语言设置
moment.locale('zh-cn');

处理 moment Deprecation warning: value provided is not in a recognized RFC2822 or ISO format

方法一:增加时间的构造参数

moment('2020-11-21', 'YYYY-MM-DD').format('YYYY-MM-DD');

方法二:关闭提示

// Suppress the warnings
const moment = require('moment');
moment.suppressDeprecationWarnings = true;

方法三:

moment(new Date("27/04/2022")).format('YYYYMMDD')

Moment.js 资源管理错误漏洞、路径遍历漏洞

在v2.29.4版本中已修复

image.png

image.png

受影响版本

v2.18.0 - v2.29.3

文档地址

Moment.js: momentjs.com/docs/