Files
bigscreenWeb/src/utils/index.ts

116 lines
3.3 KiB
TypeScript
Raw Normal View History

2025-09-25 13:32:47 +08:00
import { ElSkeletonItem } from "element-plus";
/**
* @param {date} time
* @param {String} fmt yyyy-MM-ddyyyy-MM-dd HH:mm:ss
* @returns {String}
*/
export const formatTime = (time: string | Date, fmt: string): string => {
if (!time) return "";
const date = new Date(time);
const o = {
"M+": date.getMonth() + 1,
"d+": date.getDate(),
"H+": date.getHours(),
"m+": date.getMinutes(),
"s+": date.getSeconds(),
"q+": Math.floor((date.getMonth() + 3) / 3),
S: date.getMilliseconds(),
};
if (/(y+)/.test(fmt))
fmt = fmt.replace(
RegExp.$1,
(date.getFullYear() + "").substr(4 - RegExp.$1.length)
);
for (const k in o) {
if (new RegExp("(" + k + ")").test(fmt)) {
fmt = fmt.replace(
RegExp.$1,
// @ts-ignore: Unreachable code error
RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
);
}
}
return fmt;
};
export const speak = (content: any, onComplete: Function = () => {}) => {
// 检查浏览器是否支持语音合成
if (!window.speechSynthesis) {
console.warn("当前浏览器不支持语音合成功能");
return;
}
const utterance = new SpeechSynthesisUtterance(content);
utterance.lang = "zh-CN";
utterance.rate = 1;
utterance.rate = 1.5;
// 设置结束回调(通过参数传递)
utterance.onend = () => {
onComplete();
};
// 播放语音
window.speechSynthesis.speak(utterance);
};
// 关闭语音播报
export const stopSpeak = () => {
(document.getElementById("audioId") as HTMLAudioElement)?.pause();
window.speechSynthesis.cancel();
};
/**
*
* @param {number} option - 13
* @returns {{start: Date, end: Date}} -
*/
export const getDateRange = (option: number) => {
console.log("🚀 ~ getDateRange ~ option:", option);
const now = new Date();
if (option === 1) {
//年
const firstDay = new Date(now.getFullYear(), 0, 1);
const lastDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
return formatDate(firstDay) + " 至 " + formatDate(lastDay);
}
ElSkeletonItem;
if (option === 3) {
// 获取本月日期范围
// 本月第一天
const firstDay = new Date(now.getFullYear(), now.getMonth(), 1);
// 本月最后一天
const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0);
return formatDate(firstDay) + " 至 " + formatDate(lastDay);
} else if (option === 4) {
// 获取本周日期范围
// 计算周一的日期
const monday = new Date(now);
monday.setDate(now.getDate() - now.getDay() + 1);
// 计算周日的日期
const sunday = new Date(now);
sunday.setDate(now.getDate() - now.getDay() + 7);
return formatDate(monday) + " 至 " + formatDate(sunday);
} else if (option === 6) {
// 获取本月日期范围
// 本月第一天
return formatDate(now);
}
};
/**
* YYYY-MM-DD格式
* @param {Date} date -
* @returns {string} -
*/
function formatDate(date: Date) {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, "0");
const day = String(date.getDate()).padStart(2, "0");
return `${year}-${month}-${day}`;
}