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