全网项目实战js封装方法案例

345 阅读3分钟

最近在做项目复盘的时候发现,项目里面写的好几个封装方法,都是之前写过,只是自己忘记了,又得重新去找,真是浪费时间和精力了,然后就想把之前项目封装的方法都整理一下,方便以后在开发项目中能快速找到。

数字相关方法

阿拉伯数字转汉字 (2转成二)

var chnNumChar = ["零","一","二","三","四","五","六","七","八","九"];
var chnUnitSection = ["","万","亿","万亿","亿亿"];
var chnUnitChar = ["","十","百","千"];
function SectionToChinese(section){
  var strIns = '', chnStr = '';
  var unitPos = 0;
  var zero = true;
  while(section > 0){
    var v = section % 10;
    if(v === 0){
      if(!zero){
        zero = true;
        chnStr = chnNumChar[v] + chnStr;
      }
    }else{
      zero = false;
      strIns = chnNumChar[v];
      strIns += chnUnitChar[unitPos];
      chnStr = strIns + chnStr;
    }
    unitPos++;
    section = Math.floor(section / 10);
  }
  return chnStr;
}
common.convertToChinese=(num)=>{  
    var unitPos = 0;  
    var strIns = '', chnStr = '';  
    var needZero = false;     
    if(num === 0){  
      return chnNumChar[0];  
    }     
    while(num > 0){  
      var section = num % 10000;  
      if(needZero){  
        chnStr = chnNumChar[0] + chnStr;  
      }  
      strIns = SectionToChinese(section);  
      strIns += (section !== 0) ? chnUnitSection[unitPos] : chnUnitSection[0];  
      chnStr = strIns + chnStr;  
      needZero = (section < 1000) && (section > 0);  
      num = Math.floor(num / 10000);  
      unitPos++;  
    }
    if(chnStr.length>=2){
      chnStr = chnStr.substring(chnStr.length-1,chnStr.length)
    }
    return chnStr;  
}

时间相关方法

获取当前月的第一天

common.getCurrentMonthFirst=()=>{
  var date=new Date();
  date.setDate(1);
  return common.getdateNoTime(date);
}

计算N年后,YYYYMMDD

/**
 * 计算N年后,YYYYMMDD
 * startdate:为开始时间,格式YYYYMMDD
 * nextYear:为间隔年月,如1表示一年后,2表示两年后
 */
common.getAfterNYear=(startdate,nextYear)=>{
  var expriedYear = parseInt(startdate.substring(0,4)) + nextYear;
  var expriedMonth = startdate.substring(4,6);
  var expriedDay = startdate.substring(6);
  //考虑二月份场景,若N年后的二月份日期大于该年的二月份的最后一天,则取该年二月份最后一天
  if(expriedMonth == '02' || expriedMonth == 2){
    var monthEndDate = new Date(expriedYear ,expriedMonth,0).getDate();
    if(parseInt(expriedDay) > monthEndDate){//为月底时间
      //取两年后的二月份最后一天
      expriedDay = monthEndDate;
    }
  }
  return expriedYear+expriedMonth+expriedDay;
}

获前取n天日期

common.getBeforeDate = (n) => {
  var n = n;
  var d = new Date();
  var year = d.getFullYear();
  var mon = d.getMonth() + 1;
  var day = d.getDate();
  if (day <= n) {
    if (mon > 1) {
      mon = mon - 1;
    } else {
      year = year - 1;
      mon = 12;
    }
  }
  d.setDate(d.getDate() - n);
  year = d.getFullYear();
  mon = d.getMonth() + 1;
  day = d.getDate();
  const s = year + '-' + (mon < 10 ? '0' + mon : mon) + '-' + (day < 10 ? '0' + day : day);
  return s;
};

根据两个日期,判断相差天数

/**
 * 根据bai两个日期,判断相差天数du
 * @zhiparam sDate1 开始日期 如:2016-11-01
 * @param sDate2 结束日期 如:2016-11-02
 * @returns {number} 返回相差天数
 */
common.daysBetween = (sDate1, sDate2) => {
  //Date.parse() 解析一个日期时间字dao符串,并返回1970/1/1 午夜距离该日期时间的毫秒数
  var time1 = Date.parse(new Date(sDate1));
  var time2 = Date.parse(new Date(sDate2));
  var nDays = Math.abs(parseInt((time2 - time1) / 1000 / 3600 / 24));
  return nDays;
};

根据两个日期,判断相差月数

/**
 * 根据bai两个日期,判断相差月数
 * @zhiparam sDate1 开始日期 如:2016-11-01
 * @param sDate2 结束日期 如:2016-11-02
 **/
common.getIntervalMonth = (startDate, endStart) => {
  var startMonth = new Date(startDate).getMonth();
  var endMonth = new Date(endStart).getMonth();
  var intervalMonth =
    new Date(endStart).getFullYear() * 12 + endMonth - (new Date(startDate).getFullYear() * 12 + startMonth);
  return intervalMonth;
};

获取几个月前的输入日期

/**
 *获取几个月前的输入日期
 *{param:DateTime} date 输入日期(YYYY-MM-DD)
 *{param:number } monthNum 月数
 */
common.GetPreMonthDay = (date, monthNum) => {
  var dateArr = date.split('-');
  var year = dateArr[0]; //获取当前日期的年份
  var month = dateArr[1]; //获取当前日期的月份
  var day = dateArr[2]; //获取当前日期的日
  var days = new Date(year, month, 0);
  days = days.getDate(); //获取当前日期中月的天数
  var year2 = year;
  var month2 = parseInt(month) - monthNum;
  if (month2 <= 0) {
    var absM = Math.abs(month2);
    year2 = parseInt(year2) - Math.ceil(absM / 12 == 0 ? 1 : parseInt(absM) / 12);
    month2 = 12 - (absM % 12);
  }
  var day2 = day;
  var days2 = new Date(year2, month2, 0);
  days2 = days2.getDate();
  if (day2 > days2) {
    day2 = days2;
  }
  if (month2 < 10) {
    month2 = '0' + month2;
  }
  var t2 = year2 + '-' + month2 + '-' + day2;
  return t2;
};

时间戳转换时间

/**
 *时间戳转换时间
 *@param  date 转入参数是 时间戳
 */
common.getdate = (date) => {
  var now = new Date(date),
    y = now.getFullYear(),
    m = now.getMonth() + 1,
    d = now.getDate();
  return y + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d) + ' ' + now.toTimeString().substr(0, 8);
};

时间戳转换时间 - 无时分秒*/

/* 时间戳转换时间 - 无时分秒*/
common.getdateNoTime = (date) => {
  var now = new Date(date),
    y = now.getFullYear(),
    m = now.getMonth() + 1,
    d = now.getDate();
  return y + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d);
};

获取当前日期

common.formatting = (time) => {
  let date = new Date();
  if (time !== undefined) {
    date = new Date(time);
  }
  const seperator1 = '-';
  const year = date.getFullYear();
  let month = date.getMonth() + 1;
  let strDate = date.getDate();
  if (month >= 1 && month <= 9) {
    month = `0${month}`;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = `0${strDate}`;
  }
  const currentdate = year + seperator1 + month + seperator1 + strDate;
  return currentdate;
};

获取开始时间和结果时间之间的毫秒值数据

/**
 *获取开始时间和结果时间之间的毫秒值数据 
 * @zhiparam startTime 开始日期 如: Thu Apr 29 2021 15:15:19 GMT+0800 (中国标准时间)
 * @param endTime 结束日期 如:Thu Apr 29 2021 14:15:19 GMT+0800 (中国标准时间)
 * @returns 返回值  数组
 */
common.getAllDateCN = (startTime, endTime) => {
  var date_all = [];
  var i = 0;
  while (endTime.getTime() - startTime.getTime() >= 0) {
    // console.log(common.getdate(startTime),common.getdate(endTime))
    date_all[i] = common.getdateTime(startTime);
    startTime = new Date(Date.parse(startTime) + 1000);
    i += 1;
  }
  return date_all;
};
// 实例
let date1 = new Date()
let date2 = new Date(date1-1*60*60*1000)
console.log('getAllDateCN',common.getAllDateCN(date2,date1))

文字转语音

/**
 * 文字转语音,利用H5的新特性SpeechSynthesisUtterance,speechSynthesis实现
  *@param  text 转入参数是 字符串文本
 */
common.Speaker =(text)=>{
  let msg = new SpeechSynthesisUtterance();
  msg.text = text // 要合成的文本
  msg.lang = "zh-CN" // 中文发音(默认自动选择)
  msg.rate = 1  // 二倍速(默认为 1,范围 0.110msg.pitch = 1 // 高音调(数字越大越尖锐,默认为 1,范围 02msg.volume = 1 // 音量 0.5 倍(默认为1,范围 01)
  window.speechSynthesis.speak(msg);
}