在Vue项目中难免会经常遇到需要操作日期,获取日期等操作,一般大家都是通过new Date()去一步一步获取,这样做非常麻烦。今天给大家介绍一个功能强大,代码量少,快捷又方便的日期处理插件—moment.js。
1、安装
npm install vue-moment --save
2、在main.js中使用
import moment from 'moment'//导入文件
Vue.prototype.$moment = moment;//赋值使用
3、常用的一些日期格式化方法
1)日期格式化
this.$moment().format('MMMM Do YYYY, h:mm:ss a'); // May 14th 2023, 11:37:40 am
this.$moment().format('dddd'); // Sunday
this.$moment().format("MMM Do YY"); // May 14th 23
this.$moment().format('YYYY [escaped] YYYY'); // 2023 escaped 2023
this.$moment().format(); // 2023-05-14T11:41:27+08:00
2)相对时间
this.$moment("20161031", "YYYYMMDD").fromNow(); // 7 years ago
this.$moment("20120620", "YYYYMMDD").fromNow(); // 11 years ago
this.$moment().startOf('day').fromNow(); // 12 hours ago
this.$moment().endOf('day').fromNow(); // in 12 hours
this.$moment().startOf('hour').fromNow(); // an hour ago
3)日历时间
this.$moment().subtract(10, 'days').calendar(); // 05/04/2023
this.$moment().subtract(6, 'days').calendar(); // Last Monday at 11:46 AM
this.$moment().subtract(3, 'days').calendar(); // Last Thursday at 12:20 PM
this.$moment().subtract(1, 'days').calendar(); // Yesterday at 12:21 PM
this.$moment().calendar(); // Today at 12:25 PM
this.$moment().add(1, 'days').calendar(); // Tomorrow at 12:26 PM
this.$moment().add(3, 'days').calendar(); // Wednesday at 12:26 PM
this.$moment().add(10, 'days').calendar(); // 05/24/2023
4)多语言支持
this.$moment().format('L'); // 05/14/2023
this.$moment().format('l'); // 5/14/2023
this.$moment().format('LL'); // May 14, 2023
this.$moment().format('ll'); // May 14, 2023
this.$moment().format('LLL'); // May 14, 2023 12:28 PM
this.$moment().format('lll'); // May 14, 2023 12:29 PM
this.$moment().format('LLLL'); // Sunday, May 14, 2023 12:29 PM
this.$moment().format('llll'); // Sun, May 14, 2023 12:29 PM
4、说明文档
格式代码 | 说明 | 返回值 |
---|---|---|
YYYY | 四位数字完整表示的年份 | 如:1999 或 2019 |
M | 数字表示的月份,没有前导零 | 1 ~ 12 |
MM | 数字表示的月份,没有前导零 | 01 ~ 12 |
MMM | 三个字母缩写表示的月份 | 一月 ~ 十二月 |
MMMM | 数字表示的月份,没有前导零 | 一月 ~ 十二月 |
M | 月份,完整的文本格式 | 1 ~ 12 |
D | 月份中的第几天,没有前导零 | 1 ~ 31 |
DD | 月份中的第几天,有前导零 | 01 ~ 31 |
d | 星期中的第几天,数字表示 | 0 ~ 6,0 表示周日,6 表示周六 |
ddd | 三个字母表示星期中的第几天 | 星期日 ~ 星期六 |
dddd | 星期几,完整的星期文本 | 星期日 ~ 星期六 |
HH | 小时,24小时制,有前导零 | 00 ~ 23 |
H | 小时,24小时制,无前导零 | 0 ~ 23 |
hh | 小时,12小时制,有前导零 | 00 ~ 12 |
h | 小时,12小时制,无前导零 | 0 ~ 12 |
mm | 分钟,有前导零 | 00 ~ 59 |
m | 分钟,没有前导零 | 0 ~ 59 |
ss | 秒,有前导零 | 01 ~ 59 |
s | 秒,无前导零 | 1 ~ 59 |