Files
dyf-vue-ui/src/utils/common.ts
2025-09-11 11:10:53 +08:00

118 lines
3.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//日期格式化
function DateFormat(date, format) {
if (!date) {
return '';
}
if (!format) {
format = 'yyyy-MM-dd HH:mm:ss';
}
// 处理参数默认值
if (typeof date === 'string' || typeof date === 'number') {
date = new Date(date);
}
date = date instanceof Date ? date : new Date();
format = format || 'yyyy-MM-dd';
// 检查日期是否有效
if (isNaN(date.getTime())) {
return 'Invalid Date';
}
// 定义格式化映射
const formatMap = {
'yyyy': date.getFullYear(),
'MM': String(date.getMonth() + 1).padStart(2, '0'),
'dd': String(date.getDate()).padStart(2, '0'),
'HH': String(date.getHours()).padStart(2, '0'),
'mm': String(date.getMinutes()).padStart(2, '0'),
'ss': String(date.getSeconds()).padStart(2, '0'),
'SSS': String(date.getMilliseconds()).padStart(3, '0'),
'M': date.getMonth() + 1,
'd': date.getDate(),
'H': date.getHours(),
'm': date.getMinutes(),
's': date.getSeconds(),
'S': date.getMilliseconds()
};
// 替换格式字符串中的占位符
return format.replace(/(yyyy|MM|dd|HH|mm|ss|SSS|M|d|H|m|s|S)/g, (match) => {
return formatMap[match];
});
}
//日期加减
function DateAdd(datePart, number, date) {
// 创建日期的副本,避免修改原日期对象
const newDate = new Date(date.getTime());
// 根据不同的时间单位添加相应的值
switch (datePart.toLowerCase()) {
case 'year':
newDate.setFullYear(newDate.getFullYear() + number);
break;
case 'month':
newDate.setMonth(newDate.getMonth() + number);
break;
case 'day':
newDate.setDate(newDate.getDate() + number);
break;
case 'hour':
newDate.setHours(newDate.getHours() + number);
break;
case 'minute':
newDate.setMinutes(newDate.getMinutes() + number);
break;
case 'second':
newDate.setSeconds(newDate.getSeconds() + number);
break;
default:
throw new Error('不支持的datePart参数。支持的参数: Year, Month, Day, Hour, Minute, Second');
}
return newDate;
}
//将字节转换成0.53kb 10.13MB 1GB这样的友好单位
function formatBytes(bytes, decimals = 2) {
// 处理0字节的情况
if (bytes === 0) return '0 B';
// 定义单位和换算比例
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
// 计算最合适的单位
const i = Math.floor(Math.log(bytes) / Math.log(k));
// 格式化并返回结果
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
//数组某个字段取唯一值
function getUniqueValues(dataSource, field) {
if(!field){
return [];
}
// 使用Set来存储唯一值因为Set会自动去重
const uniqueValues = new Set();
// 遍历数据源
for (const item of dataSource) {
// 检查对象是否包含指定字段
if (item.hasOwnProperty(field)) {
uniqueValues.add(item[field]);
}
}
// 将Set转换为数组并返回
return Array.from(uniqueValues);
}
export default{
DateFormat:DateFormat,
DateAdd:DateAdd,
formatBytes:formatBytes,
getUniqueValues:getUniqueValues
}