一, 介绍及安装
1.1 介绍
Moment.JS 是一个优秀的 JavaScript 日期处理类库.
如果没有 Moment.JS 之类的日期处理库, 我们如果需要获得格式化后的日期. 往往需要通过 new Date().getMonth()... 之类方法进行拼接, 或者使用 JQ 封装的函数. 但现在但 SPA 页面不怎么使用 JQ. 所以掌握靠谱的 Moment.JS 还是很有必要的
举个小小例子:
请听题: 通过原生 JS 和 moment.JS 分别获取 moment().format('MMMM Do YYYY, h:mm:ss)格式的时间
- const js_date = new Date();
- const moment_date = moment();
- console.log('js new Date() ==========>', `${js_date.getFullYear()}-${js_date.getMonth() + 1}-${js_date.getDate()} ${js_date.getHours()}:${js_date.getMinutes()}:${js_date.getSeconds()}`)
- console.log('moment moment() ==========>', moment_date.format('YYYY-MM-DD HH:mm:ss'))
输出结果:
- JS new Date() ==========> 2018-11-1 18:0:59
- moment moment() ==========> 2018-11-01 18:00:59
momentjs 优势之处显而易见
1.2 安装
环境 | 安装方式 | 引入例子 | 描述 |
---|---|---|---|
Node.js | npm install moment -D | 1⃣️ | 通常用在 react、vue 等单页面项目 |
浏览器 | 可官网单独下载 js, 也可以通过 npm install moment, 然后引入里面的 js | 2⃣️️ | 一般直接在 html 文件里使用 |
1⃣ Node.JS(React,Vue):
- // 导入
- import moment from 'moment' //ES6
- const moment = require('moment') //AMD 规范
- // 使用
- let nowTime = moment() // 当前时间
- ...
2⃣ 浏览器(.HTML): 本文的案例均采用这种方式
- // 导入
- <script src="xxx/moment.js"></script> //JS 文件既可以自己去官网首页下载, 也可以通过 NPM install moment 获得
- const moment = moment(); // 当前时间
二, API 大全
2.1 解析时间格式
解析时间格式意思就是当传入某个时间字符串的时候, moment.JS 可以解析出 YYYY-MM-DD 之类的格式
语法:
moment(时间内容 - String)
例子:
- var analysisMoment = moment("1995-12-25");
- console.log(analysisMoment)
输出的部分结果:
- _d: Mon Dec 25 1995 00:00:00 GMT+0800 (CST) {
- }
- _f: "YYYY-MM-DD"
- _i: "1995-12-25"
- _isAMomentObject: true
- _isUTC: false
- _isValid: true
甚至还可以解析出[1995, 12, 25]
2.2 转换时间格式
这个功能是我们经常会用到的. 也是文章最开始举例使用的方法.
语法:
- moment(内容 - String).format(格式 - String)
- const dateString = '2018-11-01'
- const transformFormat = moment(dateString).format('YYYY MM DD')
- console.log('transformFormat =========>', transformFormat)
只要 Y,M,D,H,m,s... 写对了, 无论转换成什么格式都可以!
- momemt('20181101').format('YY 年 MM 月 DD 日')
- // 输出 18 年 11 月 01 日
2.3 创建 / 调整日期
创建日期例子:
moment({ y: 2018, Month: 11, day: 01, hour:15, minute:10 });
修改日期:
语法:
moment().seconds() === new Date().getSeconds();
同理还有:
毫秒: millsecond(Number)
分钟: minute(Number)
星期: day(Number|String
年: year(Number)
...
例子:
- console.log('修改月份为二月 =========>', moment().month('Feb').format('YYYY MM DD') )
- console.log('修改当前时间的小时为九点: 下班 =========>', moment().seconds(30).format('YYYY MM DD HH:mm'))
输出结果:
修改当前时间的月份为二月 =========> 2018 02 01
修改当前时间的小时为九点: 下班 =========> 2018 11 01 20:05
2.3 日期操作方法
增加 / 减少日期
语法:
- moment().add(Number, String);
- moment().add(Duration);
- moment().add(Object);
例子: 在当前时间增加 / 减少 7 天
- // 方式一 (Number, String)
- console.log('当前时间增加 7 天:', moment().add(7, 'd').format('YYYY MM DD'))
- console.log('当前时间减少两个月', moment().subtract(2, 'months').format('YYYY-MM-DD'))
- // 方式二, 三 (二可结合 moment.duration())
- console.log('当前时间增加 2 天', moment().add({
- 'day': 2
- }).format('YYYY-MM-DD'))
- /*** 输出 ***/
- // 方式一
当前时间增加 7 天: 2018-11-08
当前时间减少两个月 2018-09-01
// 方式二
当前时间增加 2 天 2018-11-03
2.4 日期相关显示
时间差显示
和当前时间比较
语法:
- // 以当前时间为基准进行对比
- moment().fromNow(Boolean); // 之前
- moment().toNow(); // 之后
- // 布尔值可省略, 如加上则只显示时间差
例子:
- console.log('2008 年和今天:', moment([2008, 11, 1]).fromNow())
- console.log('2008 年和今天相差:', moment([2008, 11, 1]).fromNow(true))
- // 输出
2008 年和今天: 10 years ago
2008 年和今天相差: 10 years
和之前 / 之后时间比较
语法:
- moment().from(Moment|String|Number|Date|Array, Boolean); // 之前
- moment().to(Moment|String|Number|Date|Array, Boolean); // 之后
例子:
- //from
- var a = moment([2007, 0, 28]);
- var b = moment([2007, 0, 29]);
- a.from(b); // "a day ago"
- a.from([2007, 0, 29]); // "a day ago"
- a.from(new Date(2007, 0, 29)); // "a day ago"
- a.from("2007-01-29"); // "a day ago"
其他
简写 (key <=> Shorthand) 对比表可以参考:
《Momentjs docs》 http://momentjs.cn/docs/#/manipulating/max/
《Moment.JS 官网》 http://momentjs.cn/
来源: https://www.cnblogs.com/soyxiaobi/p/9888593.html