Skip to main content

momentjs

官方文档

安装

npm install moment --save   # npm
yarn add moment # Yarn
Install-Package Moment.js # NuGet
spm install moment --save # spm
meteor add momentjs:moment # meteor
yarn add @types/moment -D

基础使用

日期格式化

moment().format('MMMM Do YYYY, h:mm:ss a'); // 四月 42022, 9:22:30 上午
moment().format('dddd'); // 星期一
moment().format("MMM Do YY"); // 4422
moment().format('YYYY [escaped] YYYY'); // 2022 escaped 2022
moment().format(); // 2022-04-04T09:22:30+08:00

相对时间

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

日历时间

moment().subtract(10, 'days').calendar(); // 2022/03/25
moment().subtract(6, 'days').calendar(); // 上星期二09:22
moment().subtract(3, 'days').calendar(); // 上星期五09:22
moment().subtract(1, 'days').calendar(); // 昨天09:22
moment().calendar(); // 今天09:22
moment().add(1, 'days').calendar(); // 明天09:22
moment().add(3, 'days').calendar(); // 下星期四09:22
moment().add(10, 'days').calendar(); // 2022/04/14

多语言支持

moment.locale();         // zh-cn
moment().format('LT'); // 09:22
moment().format('LTS'); // 09:22:30
moment().format('L'); // 2022/04/04
moment().format('l'); // 2022/4/4
moment().format('LL'); // 2022年4月4日
moment().format('ll'); // 2022年4月4日
moment().format('LLL'); // 2022年4月4日上午9点22分
moment().format('lll'); // 2022年4月4日 09:22
moment().format('LLLL'); // 2022年4月4日星期一上午9点22分
moment().format('llll'); // 2022年4月4日星期一 09:22

使用示例

const moment = require('moment')

function Now(f = 'YYYY-M-DD_HH:mm:ss') {
return moment().format(f);
}

function Format(t) {
moment(t, 'YYYY-M-DD_h:mm:ss').format('YYYY-M-DD_HH:mm:ss');
}
/**
* @Description - 返回当前时间
*
* @param {string} format -格式
*
* ```js
* // 常用格式:
* 'YYYY-M-DD_HH:mm:ss'
* 'YYYY-M-DD'
* ```
*
*/
export async function currtTime(format: string = "YYYY-M-DD_HH:mm:ss") {
return moment().format(format);
}