js封装文件
// 获取当年的节假日12个月的数据
let holidaysArr = [
[1, 4, 5, 11, 12, 18, 19, 25, 26, 27, 28, 29, 30, 31], // 1月
[1, 2, 3, 4, 5, 6, 9, 15, 16, 22, 23], // 2月
[], // 3月
[4, 5, 6, 12, 13, 19, 20, 26], // 4月
[1, 2, 3, 4, 5, 10, 11, 17, 18, 24, 25, 31], // 5月
[1, 2, 7, 8, 14, 15, 21, 22, 28, 29], // 6月
[], // 7月
[], // 8月
[6, 7, 13, 14, 20, 21, 27], // 9月
[1, 2, 3, 4, 5, 6, 7, 8, 12, 18, 19, 25, 26], // 10月
[], // 11月
[], // 12月
];
// 获取当前时间
const now = new Date();
// 获取当前年月日
const currentYear = now.getFullYear();
const currentMonth = now.getMonth() + 1; //获取的月份是0-11所以加1
const currentDay = now.getDate();
// 获取当月有多少天工作日
function getWorkDaysInMonth(month) {
// 月份的天数 月份参数是0-11,日参数0表示上一个月的最后一天 所以月份不用减一,如果日参数不是0,则月份要减一
let daysInMonth = new Date(currentYear, month, 0).getDate();
// 总工作日
let workDays = 0;
// 判断当前月份是否有节假日
let holidays = holidaysArr[month - 1];
if (holidays.length > 0) {
workDays = daysInMonth - holidays.length;
} else {
for (let i = 1; i <= daysInMonth; i++) {
let date = new Date(currentYear, month - 1, i);
let day = date.getDay(); // 0-6,0代表星期天
if (day !== 0 && day !== 6) {
workDays++;
}
}
}
// console.log(month + "月有", workDays + "个工作日");
return workDays;
}
// 获取当月已过工作日
function getPassedWorkDaysInMonth(month) {
// 已过工作日
let passedWorkDays = 0;
// 判断当前月份是否有节假日
let holidays = holidaysArr[month - 1];
if (holidays.length > 0) {
// 节假日已过工作日
for (let i = 1; i <= currentDay; i++) {
if (!holidays.includes(i)) {
passedWorkDays++;
}
}
} else {
// 无节假日已过工作日
for (let i = 1; i <= currentDay; i++) {
let date = new Date(currentYear, month - 1, i);
let day = date.getDay(); // 0-6,0代表星期天
if (day !== 0 && day !== 6) {
passedWorkDays++;
}
}
}
// console.log(month + "月已过", passedWorkDays + "个工作日");
return passedWorkDays;
}
// 获取当月时间进度
export function getMonthProgress() {
let num =
getPassedWorkDaysInMonth(currentMonth) / getWorkDaysInMonth(currentMonth);
// console.log("当月时间进度为",(num * 100).toFixed(2).replace(/\0$/, "").replace(/\.0$/, "") + "%");
return num;
}
// 获取年工作时间进度
export function getYearProgress() {
// 年总工作日
let yearWorkDays = 0;
// 年已过工作日
let passedWorkDays = 0;
for (let i = 1; i <= 12; i++) {
yearWorkDays += getWorkDaysInMonth(i);
// 已过工作日
if (i < currentMonth) {
passedWorkDays += getWorkDaysInMonth(i);
} else if (i == currentMonth) {
passedWorkDays += getPassedWorkDaysInMonth(i);
}
}
// console.log("年工作日进度", ((passedWorkDays / yearWorkDays) * 100).toFixed(2).replace(/\0$/, "").replace(/\.0$/, "") + "%");
return (
((passedWorkDays / yearWorkDays) * 100)
.toFixed(2)
.replace(/\0$/, "")
.replace(/\.0$/, "") + "%"
);
}
引入
import { getMonthProgress, getYearProgress } from "@/utils/date.js";
使用
// 当月时间进度
this.less_day = (getMonthProgress() * 100).toFixed(1).replace(/\.0$/, "") + "%";
// 时间线的定位
this.less_day2 = (getMonthProgress() * 270).toFixed(1).replace(/\.0$/, "") + "px";
// 年时间进度
this.yearProgress = getYearProgress();
结果