vue的日历时间、日期加减计算
在开发中,会遇到日期的计算,像是一些剩余时间、或者已过时间,会用到 dayjs 中的将日期(xx年xx月xx年)这样的string字符型日期时间转换为 时间戳,在进行加减运算
1.项目中dayjs引入
- 在项目中安装 dayjs(它是一个轻量的处理时间和日期的javascript库)
npm install dayjs --save
- 在main.js 添加两句代码
- 引入 dayjs 库文件
import dayjs from 'dayjs';
- 定义的全局变量
Vue.prototype.dayjs = dayjs;
- 引入 dayjs 库文件
- 在需要的页面中直接使用(已经在main.js里面定义了全局变量的使用 )
2.项目中dayjs库的使用:
-
月日年表达各有不同,如下
- 年 YY 月 MM 日 DD 时 HH 分 mm 秒 ss
- 当前日期转时间戳直接转换,format后面就跟想要个格式化的内容,dayjs()括号中不放任何参数,默认为当前时间
this.dayjs().format("YYYY-MM-DD");//2022-09-29 this.dayjs().format("YYYY-MM-DD HH-mm");//2022-09-29 15:17:54 this.dayjs( 1664435896).format("YYYY-MM-DD HH-mm-ss");//2022-09-29 15:17:54
-
计算 某周/某月/某年 的起始截止时间
-
所用到方法为
starOf()
、starOf()
、endOf()
、括号中可以是:week、month、year
this.dayjs().starOf("week");//指的是本周开始时间 this.dayjs().endOf("month").format('YYYY-MM-DD');//指的是本月截止时间 this.dayjs("2022-6-14").endOf("month").format('YYYY-MM-DD');//指定月份的那一个月的截止时间
-
-
计算 日期 ”前几天“ 、 ”后几天“
-
前(减)后(加)
subtract(参数1,参数2)
、add(参数1,参数2)
-
参数1 是数字 参数2 是单位(周、月、年)
this.dayjs().substract(3,'day').format("YYYY-MM-DD");//今天的前3天 this.dayjs().add(3,'month').format("YYYY-MM-DD");//今天的后三个月 this.dayjs('2022-6-10').add(6,'week').format("YYYY-MM-DD");//2022-6-10号的后六周
-
-
获取月天数,使用方法
dayInMonth()
this.dayjs()dayInMonth();//获取本月天数
-
普通日期转换为时间戳
this.dayjs().unix();//获取当前时间时间戳 this.dayjs('2022-10-1').unix();//获取指定时间时间戳