dashengzi66 / note

学习笔记
0 stars 0 forks source link

工具函数 #11

Open dashengzi66 opened 3 years ago

dashengzi66 commented 3 years ago

格式化时间

/*
* formatTime:时间字符串的格式化处理
*   @params
*   templete:[string] 我们最后期望获取日期格式的模板
*   模板规则:{0}->年  {1~5}->月日时分秒
*   @return
*   [string]格式化后的时间字符串
*/
function formatTime(templete = "{0}年{1}月{2}日 {3}时{4}分{5}秒") {
    let timeAry = this.match(/\d+/g);
    return templete.replace(/\{(\d+)\}/g, (...[, $1]) => {
        let time = timeAry[$1] || "00";
        return time.length < 2 ? "0" + time : time;
    });
}
dashengzi66 commented 3 years ago
/* 
* queryURLParams:获取URL地址问号和面的参数信息(可能也包含HASH值)
* @params
* @return
* [object]把所有问号参数信息以键值对的方式存储起来并且返回
*/

function queryURLParams() {
  let obj = {};
  this.replace(/([^?=&#]+)=([^?=&#]+)/g, (...[, $1, $2]) => obj[$1] = $2);
  this.replace(/#([^?=&#]+)/g, (...[, $1]) => obj['HASH'] = $1);
  return obj;
}
dashengzi66 commented 3 years ago
/* 
* millimeter:实现大数字的千分符处理
* @params
* @return
* [string]千分符后的字符串
*/
function millimeter() {
   return this.replace(/\d{1,3}(?=(\d{3})+$)/g, content => content + ',');
}
dashengzi66 commented 3 years ago

小数相加

numberAdd(arr) {
  let d = 0, //定义小数位的初始长度,默认为整数,即小数位为0
        sum = 0;
   for (var key in arr) {
      var str = "" + arr[key];
      if (str.indexOf(".") != -1) {
          //获取小数位的长度
          var temp = str.split(".")[1].length;
          //比较此数的小数位与原小数位的长度,取小数位较长的存储到d中
          d = d < temp ? temp : d;
        }
   }
   let m = Math.pow(10, d);
   for (var key in arr) {
     sum += arr[key] * m;
   }
   return sum / m;
  }
dashengzi66 commented 3 years ago

获取当前时间前后N天前后日期的方法

function GetDateStr(AddDayCount) { var dd = new Date(); dd.setDate(dd.getDate() + AddDayCount); //获取AddDayCount天后的日期 var y = dd.getFullYear(); var m = (dd.getMonth() + 1) < 10 ? "0" + (dd.getMonth() + 1) : (dd.getMonth() + 1); //获取当前月份的日期,不足10补0 var d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate(); //获取当前几号,不足10补0 return y + "-" + m + "-" + d; } console.log("半年前:" + GetDateStr(-180)); console.log("三月前:" + GetDateStr(-90)); console.log("一月前:" + GetDateStr(-30)); console.log("昨天:" + GetDateStr(-1)); console.log("今天:" + GetDateStr(0)); console.log("明天:" + GetDateStr(1)); console.log("后天:" + GetDateStr(2)); console.log("一月后:" + GetDateStr(30)); console.log("三月后:" + GetDateStr(90)); console.log("半年后:" + GetDateStr(180));