Moment.js

Moment.js是一个轻量级的JavaScript时间库,它方便了日常开发中对时间的操作,提高了开发效率。这个在一些金融保险公司会经常用到,比如一下时间的格式化处理,时间的选择等等。

这个比较好的地方是可以格式化时间(很常用),日历的选择、多语言支持等等。

Moment.js日期处理库的使用_大数据

几种安装方式(选择其中一种即可)

npm install moment --save

# npm

yarn add moment

# Yarn

Install-Package Moment.js

# NuGet

spm install moment --save

# spm

meteor add momentjs:moment

# meteor

官方文档

​http://momentjs.cn/">http://momentjs.cn/​

moment.js下载

​http://cdn.staticfile.org/moment.js/2.24.0/moment.js">http://cdn.staticfile.org/moment.js/2.24.0/moment.js​

moment.js多语言下载

​http://cdn.staticfile.org/moment.js/2.24.0/moment-with-locales.js">http://cdn.staticfile.org/moment.js/2.24.0/moment-with-locales.js​

引入

<script src="moment.js"></script>
<script>
moment().format();
</script>

var moment = require('moment');
moment().format();

日期格式化

moment().format('MMMM Do YYYY, h:mm:ss a'); // 十二月 16日 2021, 4:22:44 下午
moment().format('dddd'); // 星期四
moment().format("MMM Do YY"); // 12月 16日 21
moment().format('YYYY [escaped] YYYY'); // 2021 escaped 2021
moment().format(); // 2021-12-16T16:22:44+08:00

相对时间

moment("20111031", "YYYYMMDD").fromNow(); // 10 年前
moment("20120620", "YYYYMMDD").fromNow(); // 9 年前
moment().startOf('day').fromNow(); // 16 小时前
moment().endOf('day').fromNow(); // 8 小时内
moment().startOf('hour').fromNow(); // 23 分钟前

日历时间

moment().subtract(10, 'days').calendar(); // 2021/12/06
moment().subtract(6, 'days').calendar(); // 上星期五16:22
moment().subtract(3, 'days').calendar(); // 上星期一16:22
moment().subtract(1, 'days').calendar(); // 昨天16:22
moment().calendar(); // 今天16:22
moment().add(1, 'days').calendar(); // 明天16:22
moment().add(3, 'days').calendar(); // 下星期日16:22
moment().add(10, 'days').calendar(); // 2021/12/26

多语言支持

moment.locale();         // zh-cn
moment().format('LT'); // 16:22
moment().format('LTS'); // 16:22:44
moment().format('L'); // 2021/12/16
moment().format('l'); // 2021/12/16
moment().format('LL'); // 2021年12月16日
moment().format('ll'); // 2021年12月16日
moment().format('LLL'); // 2021年12月16日下午4点22分
moment().format('lll'); // 2021年12月16日 16:22
moment().format('LLLL'); // 2021年12月16日星期四下午4点22分
moment().format('llll'); // 2021年12月16日星期四 16:22


好啦,本期内容就分享到这里,我们下期见!

Moment.js日期处理库的使用_大数据_02