Loading

moment插件的使用姿势

moment插件的使用姿势

1. 日期格式化

moment().format('MMMM Do YYYY, h:mm:ss a'); // 三月 7日 2020, 11:59:47 中午
 
moment().format('dddd');                    // 星期六
 
moment().format("MMM Do YY");               // 3月 7日 20
 
moment().format('YYYY [escaped] YYYY');     // 2020 escaped 2020

moment().format();                          // 2020-03-07T11:59:47+08:00

2. 相对时间

moment("20111031", "YYYYMMDD").fromNow(); // 8 年前

moment("20120620", "YYYYMMDD").fromNow(); // 8 年前

moment().startOf('day').fromNow();        // 12 小时前

moment().endOf('day').fromNow();          // 12 小时内

moment().startOf('hour').fromNow();       // 1 小时前

3. 日历时间

moment().subtract(10, 'days').calendar(); // 2020/02/26

moment().subtract(6, 'days').calendar();  // 上星期日11:59

moment().subtract(3, 'days').calendar();  // 上星期三11:59

moment().subtract(1, 'days').calendar();  // 昨天11:59

moment().calendar();                      // 今天11:59

moment().add(1, 'days').calendar();       // 明天11:59

moment().add(3, 'days').calendar();       // 下星期二11:59

moment().add(10, 'days').calendar();      // 2020/03/17

4. 其他格式

moment.locale();         // zh-cn

moment().format('LT');   // 11:59
 
moment().format('LTS');  // 11:59:47

moment().format('L');    // 2020/03/07

moment().format('l');    // 2020/3/7

moment().format('LL');   // 2020年3月7日

moment().format('ll');   // 2020年3月7日

moment().format('LLL');  // 2020年3月7日中午11点59分

moment().format('lll');  // 2020年3月7日 11:59

moment().format('LLLL'); // 2020年3月7日星期六中午11点59分

moment().format('llll'); // 2020年3月7日星期六 11:59

5. 常用格式

moment().format("YYYY年MM月DD日 HH时mm分ss秒"); //2020年04月20日 18时59分50秒

moment(1711641720000).format('YYYY-MM-DD HH:mm:ss'); //2020-04-20 18:59:50(24小时制)
 
moment(1711641720000).format('YYYY-MM-DD hh:mm:ss'); //2020-04-20 06:59:50(12小时制)

6. 工作中常用总结

const moment = require('moment')

// 现在北京时间 2021-11-24 17:00:00

// 1. 设置为当年1月1日00:00, 即 2021-01-01
moment().startOf('year')

// 2. 置为今年的 12 月 31 日 23:59:59.999
moment().endOf('year')

// 3. 增加时间,即 2021-11-25
moment().add(1, 'days')

// 4. 减少时间,即 2021-11-23
moment().subtract(1, 'days')

// 5. 判断18周岁
// 18周岁的当天就算满18周岁
moment().diff(moment('2003-11-24'), 'year') >= 18 // true
// 过了18周岁的当天才算满18周岁
moment().subtract(1, 'days').diff(moment('2003-11-24'), 'year') >= 18 // false

文档 | Moment.js 中文网

posted @ 2020-03-07 12:12  卡布奇诺y  阅读(1143)  评论(0编辑  收藏  举报