-
zhangwei
2026-04-07 b7ae3f69ae6706a692284d2f12835d213debfb1a
src/common/utils/util.js
@@ -117,6 +117,52 @@
      }
   },
   /**
    * 核心工具函数:根据生日字符串计算年龄
    * @param {string} birthdayStr - 生日字符串(支持 YYYY-MM-DD / YYYY/MM/DD)
    * @returns {number} 周岁(-1 表示日期无效)
    */
   calculateAgeFromBirthday(birthdayStr)  {
      console.log(birthdayStr,'、、、、、、、、、、’');
       if (!birthdayStr) return -1
       // 1. 统一格式并精准解析生日(解决 1/26 这类无补零日期的解析问题)
       const normalized = birthdayStr.replace(/[./]/g, '-')
      console.log(normalized,'normalized’');
       const [birthYear, birthMonth, birthDay] = normalized.split('-').map(Number)
       // 直接用数字创建 Date 对象,避免字符串解析的歧义(月份从 0 开始)
       const birthDate = new Date(birthYear, birthMonth - 1, birthDay)
       // 2. 校验日期合法性
       if (isNaN(birthDate.getTime())) return -1
       // 反向验证:确保输入的年月日和 Date 对象一致(避免 2010/2/30 这类无效日期)
       if (
         birthDate.getFullYear() !== birthYear ||
         birthDate.getMonth() + 1 !== birthMonth ||
         birthDate.getDate() !== birthDay
       ) {
         return -1
       }
       // 3. 获取当前日期(精准到日,排除时分秒干扰)
       const now = new Date()
       const currentYear = now.getFullYear()
       const currentMonth = now.getMonth() + 1 // 转成 1-12 月
       const currentDay = now.getDate()
       // 4. 核心:精准计算周岁
       let age = currentYear - birthYear
       // 判断:当前日期 < 生日日期 → 年龄减 1(只有当前日期 >= 生日日期,才满对应周岁)
       if (
         currentMonth < birthMonth || // 月份没到
         (currentMonth === birthMonth && currentDay < birthDay) // 月份到了,但日期没到
       ) {
         age--
       }
       // 5. 边界处理:年龄不能为负(排除未来生日)
       return age
   },
   /**
    * 日期格式转时间戳
    * @param {Object} timeStamp
    */
@@ -133,12 +179,18 @@
         parseInt(t[2], 10) || null
      )).getTime() / 1000;
   },
   minutesBetweenDates(date1, date2) {
      let dateOne = new Date(date1)
      const oneMinute = 60 * 1000; // 1分钟的毫秒数
      const difference = Math.abs(date2.getTime() - dateOne.getTime()); // 计算两个日期的毫秒差
      return Math.floor(difference / oneMinute); // 将差异转换为分钟并向下取整
   },
   formatDate(dat, type, addNum) {
      if(!dat){
      if (!dat) {
         return '-'
      }
      let date = new Date(dat)
      if(addNum){
      if (addNum) {
         date = new Date(date.setDate(date.getDate() + addNum));
      }
      const year = date.getFullYear();
@@ -147,7 +199,7 @@
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      if (type) {
         return `${year}-${month}-${day} ${hours}:${minutes}`;
         return type=='riqi' ? `${month}-${day}`: `${year}-${month}-${day} ${hours}:${minutes}`;
      }
      return `${year}-${month}-${day}`;
   },
@@ -714,7 +766,7 @@
      }
      typeof callback == 'function' && callback(theRequest);
   },
   /**
    * 路径转base64
    * @param {Object} string
@@ -739,7 +791,7 @@
            reject(error);
         };
         // #endif
         // #ifdef MP
         if (uni.canIUse('getFileSystemManager')) {
            uni.getFileSystemManager().readFile({
@@ -754,7 +806,7 @@
            })
         }
         // #endif
         // #ifdef APP-PLUS
         plus.io.resolveLocalFileSystemURL(getLocalFilePath(path), (entry) => {
            entry.file((file) => {
@@ -771,8 +823,8 @@
         // #endif
      })
   },
   roundToTwo(num){
      if(isNaN(num)){
   roundToTwo(num) {
      if (isNaN(num)) {
         return 0
      }
      return Math.round((num + Number.EPSILON) * 100) / 100;
@@ -832,5 +884,87 @@
         }
      }
   },
}
   checkFileExtensions(str) {
      const extensions = ['pdf', 'doc', 'docx', 'xls', 'xlsx'];
      return extensions.some(extension => str.includes(extension));
   },
   previewWechat(urlPdf) {
      uni.showLoading({
         title: '正在加载中..'
      })
      uni.downloadFile({
         url: urlPdf,
         success: function(res) {
            var filePath = res.tempFilePath;
            const index = urlPdf.lastIndexOf(".");
            const suffix = urlPdf.substring(index + 1);
            uni.openDocument({
               fileType: suffix,
               filePath: filePath,
               showMenu: true,
               success: function(res) {
                  console.log('打开文档成功');
                  uni.hideLoading()
               },
            });
         },
         complete: function(r) {
            uni.hideLoading()
         }
      });
   },
   //生成时间戳+随机数
   // 生成时间戳+随机数的函数
   generateTimestampWithRandom(filename) {
      // 获取当前日期和时间
      const now = new Date();
      // 获取年份,确保为四位数
      const year = now.getFullYear();
      // 获取月份,确保为两位数
      const month = String(now.getMonth() + 1).padStart(2, '0');
      // 获取日期,确保为两位数
      const day = String(now.getDate()).padStart(2, '0');
      // 获取小时,确保为两位数
      const hours = String(now.getHours()).padStart(2, '0');
      // 获取分钟,确保为两位数
      const minutes = String(now.getMinutes()).padStart(2, '0');
      // 获取秒数,确保为两位数
      const seconds = String(now.getSeconds()).padStart(2, '0');
      // 拼接时间戳
      const timestamp = `${year}${month}${day}${hours}${minutes}${seconds}`;
      // 生成一个 0 到 9999 之间的随机数,并格式化为四位数
      const randomNumber = String(Math.floor(Math.random() * 10000)).padStart(4, '0');
      // 拼接时间戳和随机数
      return `cylsg/${timestamp}_${randomNumber}` + filename.match(/\.[^.]+$/);
   },
   getFileExtensionWithDotRegex(filename) {
      const match = filename.match(/\.[^.]+$/);
      return match ? match[0] : '';
   },
   isEmpty(value) {
       return (
           value === null ||
           value === undefined ||
           value === '' ||
           (Array.isArray(value) && value.length === 0) ||
           (typeof value === 'object' &&!Array.isArray(value) && Object.keys(value).length === 0)
       );
   },
   removeEmptyValuesRecursive(obj) {
       const newObj = {};
       for (const key in obj) {
           if (obj.hasOwnProperty(key)) {
               const value = obj[key];
               if (!this.isEmpty(value)) {
                   if (typeof value === 'object' &&!Array.isArray(value)) {
                       newObj[key] = removeEmptyValuesRecursive(value);
                   } else {
                       newObj[key] = value;
                   }
               }
           }
       }
       return newObj;
   }
}