在使用vue開發(fā)項(xiàng)目時(shí),前端常常需要計(jì)算一些日期時(shí)間,如:
- 計(jì)算周月截止日期
- 計(jì)算XX天前/后的日期
- 將時(shí)間戳轉(zhuǎn)換為日期(YYYY-MM-DD)
- 計(jì)算月天數(shù)
- 日期轉(zhuǎn)時(shí)間戳
推薦一個(gè)輕量的處理時(shí)間和日期的 JavaScript 庫:dayjs
使用這個(gè)插件計(jì)算常用日期十分方便
1、在項(xiàng)目中安裝dayjs,命令為:npm install dayjs --save
2、在main.js中,添加如下2句代碼
import dayjs from "dayjs"; Vue.prototype.dayjs = dayjs;
3、在頁面需要使用的地方,直接使用
當(dāng)前日期或時(shí)間戳轉(zhuǎn)換,format后面就跟著想要格式化的內(nèi)容,**dayjs( ) **括號中不放任何參數(shù),默認(rèn)為當(dāng)前日期,也可以放一個(gè)時(shí)間戳,直接轉(zhuǎn)換
(注意:使用Element組件的日期選擇器,其value-format屬性要求:
組件 | Dayjs(format) | Element(value-format) |
---|---|---|
年 | YYYY | yyyy |
月 | MM | MM |
日 | DD | dd |
時(shí) | HH | HH |
分 | mm | mm |
秒 | ss | ss |
其中年和日的表達(dá)略有不同,容易混)
this.dayjs().format("YYYY-MM-DD") this.dayjs().format("YYYY-MM-DD HH:mm") this.dayjs(1614787200000).format("YYYY-MM-DD HH:mm:ss")
2.計(jì)算某周/某月/某年的起始截止日期,所使用到的方法為startOf(),endOf(),括號中可以是"week" 、 “month”、 “year”
(ps:加format是為了更加直觀)
this.dayjs().startOf("week"); this.dayjs().endOf("week").format("YYYY-MM-DD"); this.dayjs().startOf("month").format("YYYY-MM-DD"); this.dayjs("2021-02-09").endOf("month").format("YYYY-MM-DD");
計(jì)算日期,如幾天前、幾天后日期,
前(減) | 后(加) |
---|---|
subtract(參數(shù)1,參數(shù)2) | add(參數(shù)1,參數(shù)2) |
參數(shù)1 | 數(shù)字 |
參數(shù)2 | 單位(“week” 、 “month”、 “year”) |
this.dayjs().subtract(3,"day").format("YYYY-MM-DD") this.dayjs().subtract(3,"month").format("YYYY-MM-DD") this.dayjs().add(12,"day").format("YYYY-MM-DD") this.dayjs("2021-03-12").add(45,"day").format("YYYY-MM-DD")
5. 獲取月天數(shù),使用方法dayInMonth()
this.dayjs().daysInMonth(); this.dayjs("2021-02-09").daysInMonth(); this.dayjs("2021-01").daysInMonth();
6、普通日期轉(zhuǎn)換為時(shí)間戳
this.dayjs().unix() this.dayjs("2020-10-04").unix()
總結(jié)
到此這篇關(guān)于Vue如何使用Dayjs計(jì)算常用日期的文章就介紹到這了,更多相關(guān)Vue計(jì)算常用日期內(nèi)容請搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/Sunshine__Girl/article/details/114496906