0
点赞
收藏
分享

微信扫一扫

vue时间过滤器(moment)

_铁马冰河_ 2022-05-06 阅读 56

JavaScript 日期处理类库,用于日期格式转换的。官网地址

方法一 :局部使用

方法二:全局使用

在全局中配置(main.js文件)

// main.js
import moment from 'moment'

Vue.filter('dateFormat', (str, partten = "YYYY-MM-DD HH:mm:ss") => {
    return moment(str).format(pattern);
})
// 在组件中使用方法一:
<p class="mui-ellipsis">
    <span>发表时间: {{ item.add_time | dateFormat }} </span>
</p>

// 2022-5-6 15:53:47

// 在组件中使用方法二:
<p class="mui-ellipsis">
    <span>发表时间: {{ item.add_time | dateFormat("YYYY-MM-DD") }} </span>
</p>

// 2022-5-6

方法三:封装常用的日期处理函数

在src文件下新建utils文件夹(此文件夹一般存放自己封装的公共的工具类函数),新建tool.js文件。

//封装项目中常用的日期转换格式的函数

// 在tool.js文件中引入
import moment from "moment";

// 年-月-日
export const shortTime = function (value, formater = "YYYY-MM-DD") {
  return moment(value).format(formater);
};

// 年-月-日 时:分:秒
export const time = function (value, formater = "YYYY-MM-DD HH:mm:ss") {
  return moment(value).format(formater);
};

// 年/月/日 时:分:秒
export const time1 = function (value, formater = "YYYY/MM/DD HH:mm:ss") {
  return moment(value).format(formater);
};

// 年/月/日 时:分
export const leaveTime = function (value) {
  return moment(value).format("YYYY-MM-DD HH:mm");
};

// 年-月
export const monthTime = function (value) {
  return moment(value).format("YYYY-MM");
};

// 年/月
export const monthTime1 = function (value) {
  return moment(value).format("YYYY/MM");
};

// 年-月-日
export const monthTime2 = function (value) {
  return moment(value).format("YYYY-MM-DD");
};

// 每月第一天
export const monthOne = function (value) {
  return moment(value).format("YYYY-MM-01");
};
// 每月第一天精确
export const monthOnes = function (value) {
  return moment(value).format("YYYY-MM-01 00:00:00");
};
// 补全00:00:00
export const addZero = function (value) {
  return moment(value).format("YYYY-MM-DD 00:00:00");
};
// 月数
export const MonTime = function (value) {
  return moment(value).format("MM");
};
// 天数
export const dayTime = function (value) {
  return moment(value).format("DD");
};
// 时:分:秒
export const secondsTime = function (value) {
  return moment(value).format("HH:mm:ss");
};

// 时:分
export const secondShortTime = function (value) {
  return moment(value).format("HH:mm");
};

使用

// 在 ***.vue 页面中使用
// 引入自定义的函数名

// shortTime 是封装YYYY-MM-DD时间格式的函数名,
// time 是封装YYYY-MM-DD HH:mm:ss时间格式的函数名
import { shortTime, time } from "@/utils/tool";

let date =  new Date()          
    console.log(date)             // Fri May 06 2022 16:02:43 GMT+0800 (中国标准时间)
    console.log(shortTime(date))  // 2022-05-06
    console.log(time(date))       // 2022-05-06 16:02:43

日期格式

格式含义举例备注
yyyy2022同YYYY
M5不补0
MM01
d6不补0
dd06
dddd星期星期五
H小时824小时制;不补0
HH小时1624小时制
h小时412小时制,须和 A 或 a 使用;不补0
hh小时0412小时制,须和 A 或 a 使用
m分钟4不补0
mm分钟04
s5不补0
ss05
AAM/PMAM仅 format 可用,大写
aam/pmam仅 format 可用,小写
举报

相关推荐

0 条评论