一、Moment.js
Moment.js是一个轻量级的JavaScript时间库,它方便了日常开发中对时间的操作,提高了开发效率。这个在一些金融保险公司会经常用到,比如一下时间的格式化处理,时间的选择等等。
这个比较好的地方是可以格式化时间(很常用),日历的选择、多语言支持等等。
几种安装方式(选择其中一种即可)
安装命令 | nodejs的包管理器 |
---|---|
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/
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
引入
<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
二、Dayjs
Day.js 是一个轻量的处理时间和日期的 JavaScript 库,和 Moment.js 的 API 设计保持完全一样. 如果您曾经用过 Moment.js, 那么您已经知道如何使用 Day.js
dayjs().startOf('month').add(1,'day').set('year',2018).format('YYYY-MM-DD HH:mm:ss');
🕒 和 Moment.js 相同的 API 和用法
💪 不可变数据 (Immutable)
🔥 支持链式操作 (Chainable)
🌐 国际化 I18n
📦 仅 2kb 大小的微型库
👫 全浏览器兼容
快速开始
npm install dayjs --save
API
Day.js 有很多 API 来解析、处理、校验、增减、展示时间和日期
dayjs('2018-08-08')// 解析
dayjs().format('{YYYY} MM-DDTHH:mm:ss SSS [Z] A')// 展示
dayjs().set('month',3).month() // 获取
dayjs().add(1, 'year')// 处理
dayjs().isBefore(dayjs())// 查询
国际化 I18n
Day.js 支持国际化,但除非手动加载,多国语言默认是不会被打包到工程里的:
import 'dayjs/locale/es' // 按需加载
dayjs.locale('es') // 全局使用西班牙语
dayjs('2018-05-05').locale('zh-cn').format()// 在这个实例上使用简体中文
插件
插件是一些独立的程序,可以给 Day.js 增加新功能和扩展已有功能
import advancedFormat from 'dayjs/plugin/advancedFormat' // 按需加载插件
dayjs.extend(advancedFormat) // 使用插件
dayjs().format('Q Do k kk X x') // 使用扩展后的API