vue3时间插件之Moment.js使用教程

 更新时间:2023年09月18日 09:37:00   作者:一只爱web的羊驼  
这篇文章主要给大家介绍了关于vue3时间插件之Moment.js使用的相关资料,需要的朋友可以参考下

前言

在日期时间这一块在js中是有体现的,但是用起来不是特别方便,尤其是在vue框架中,我们也不可能去那样使用,显得很笨拙麻烦,所以给大家这次带来一个好用的时间插件,就是Moment时间插件,很小巧,使用也方便,也兼容vue3,下面来详细介绍一下

首先是Moment.js的官方网站:http://momentjs.cn/

然后下载使用插件

npm install moment --save   # npm
yarn add moment             # Yarn
Install-Package Moment.js   # NuGet
spm install moment --save   # spm
meteor add momentjs:moment  # meteor
bower install moment --save # bower (deprecated)

根据自己的需求去下载使用即可

Moment.js的配置

1.在main.js中配置如下:

import { createApp } from 'vue'
const app = createApp(App);
import moment from 'moment';
moment.locale('zh-cn');
app.config.globalProperties.$moment = moment

2.在相应的组件去使用我们的时间插件就可以了,简单举个例子:

<script setup>
import moment from "moment";
console.log(moment().format('YYYY-MM-DD dddd HH:mm:ss'));
</script>

根据自己喜欢的时间格式化使用就行

给大家分享以下常用的时间格式化的方式:

moment().format('MMMM Do YYYY, h:mm:ss a'); // 七月 25日 2023, 12:09:09 中午
moment().format('dddd');                    // 星期二
moment().format("MMM Do YY");               // 7月 25日 23
moment().format('YYYY [escaped] YYYY');     // 2023 escaped 2023
moment().format();                          // 2023-07-25T12:09:09+08:00
moment("20111031", "YYYYMMDD").fromNow(); // 12 年前
moment("20120620", "YYYYMMDD").fromNow(); // 11 年前
moment().startOf('day').fromNow();        // 12 小时前
moment().endOf('day').fromNow();          // 12 小时后
moment().startOf('hour').fromNow();       // 10 分钟前
moment().subtract(10, 'days').calendar(); // 2023/07/15
moment().subtract(6, 'days').calendar();  // 上周三12:10
moment().subtract(3, 'days').calendar();  // 上周六12:10
moment().subtract(1, 'days').calendar();  // 昨天12:10
moment().calendar();                      // 今天12:10
moment().add(1, 'days').calendar();       // 明天12:10
moment().add(3, 'days').calendar();       // 本周五12:10
moment().add(10, 'days').calendar();      // 2023/08/04
moment.locale();         // zh-cn
moment().format('LT');   // 12:10
moment().format('LTS');  // 12:10:35
moment().format('L');    // 2023/07/25
moment().format('l');    // 2023/7/25
moment().format('LL');   // 2023年7月25日
moment().format('ll');   // 2023年7月25日
moment().format('LLL');  // 2023年7月25日中午12点10分
moment().format('lll');  // 2023年7月25日 12:10
moment().format('LLLL'); // 2023年7月25日星期二中午12点10分
moment().format('llll'); // 2023年7月25日星期二 12:10

说明文档

格式代码说明返回值
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

总结 

到此这篇关于vue3时间插件之Moment.js使用的文章就介绍到这了,更多相关vue3时间插件Moment.js内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

最新评论