moment插件的安裝與使用

官方解釋moment.js是JavaScript 日期處理類庫,也就是用于日期格式轉(zhuǎn)換的。官網(wǎng)地址:http://momentjs.cn/

1.安裝
npm install moment

2.封裝常用的日期處理函數(shù)
在src文件下新建utils文件夾(此文件夾一般存放自己封裝的公共的工具類函數(shù)),新建tool.js文件。

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

封裝項目中常用的日期轉(zhuǎn)換格式的函數(shù),(日期轉(zhuǎn)換格式參考官網(wǎng)),代碼如下:

//--------------------------封裝一些常用的函數(shù)-----------------------
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");
};

// 短時間1
export const monthTime1 = function (value) {
  return moment(value).format("YYYY/MM");
};

// 短時間2
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");
};
// 月數(shù)
export const MonTime = function (value) {
  return moment(value).format("MM");
};
// 天數(shù)
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");
};

3.在index.vue頁面中使用
引入自定義的函數(shù)名

// shortTime 是封裝YYYY-MM-DD時間格式的函數(shù)名,time 是封裝YYYY-MM-DD HH:mm:ss時間格式的函數(shù)名
import { shortTime, time } from "@/utils/tool";
let date =  new Date()          
    console.log(date)
    console.log(shortTime(date))      //短時間
    console.log(time(date))           //長時間
打印結(jié)果.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容