1. 程式人生 > >個人做微信小程式開發用到的工具類

個人做微信小程式開發用到的工具類

/*
 * 功能:通用工具類
 *
 * 描述:小程式常用到的一些處理方法集合
 * 建立日期:2018-3-27
 * 更新日期:2018-7-17
 */
export default {
    // 常用正則,使用方法:utils.regular.mobile.test(str),驗證通過返回true,驗證失敗返回false
    regular: {
        email: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/, //驗證郵箱
        mobile: /^1(0|1|2|3|4|5|6|7|8|9)\d{9}$/, //驗證手機號碼
        telphone: /^(0[0-9]{2,3}\-)([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$/, //驗證固話
        idcard: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, // 驗證身份證,支援15位和18位身份證
        password: /^[a-zA-Z]\w{6,18}$/, // 以字母開頭,長度在6~18之間,只能包含字母、數字和下劃線
        postcode: /^[1-9]\d{5}$/ //郵政編碼
    },
    /*
     * 設定storage快取(同步)
     */
    setStorage(key, data) {
        wx.setStorageSync(key, data);
    },
    /*
     * 從storage快取得到資料(同步)
     */
    getStorage(key) {
        return wx.getStorageSync(key) || null;
    },
    /*
     * 從storage快取刪除資料(同步)
     */
    removeStorage(key) {
        wx.removeStorageSync(key);
    },
    /*
     * 從storage快取清除所有的資料(同步)
     */
    clearStorage() {
        wx.clearStorageSync();
    },
    /**
     * 數字補零
     * 
     * @param str:要補齊零的數字
     * @param num:補零的個數,預設是1個
     */
    digit(str, num = 1) {
        str = str.toString();
        return str[1] ? str : '0' + str;
    },
    /*
     * 判斷是否是數字
     */
    isNumber(str) {
        return !this.isNull(str) ? !isNaN(str) : false;
    },
    /**
     * 判斷兩個值是否相等
     * 注:強制比較,包括同一個字元,但是不同型別
     */
    equals(arg1, arg2) {
        return Object.is(arg1, arg2);
    },
    /**
     * 
     * 判斷是否是整數
     */
    isInteger(str) {
        return Number.isInteger(str);
    },
    /*
     * 判斷資料是否為空,可以驗證字串和陣列和Object
     */
    isNull(obj) {
        return (obj == undefined || obj == null || obj == "" || obj.length == 0 || (obj == null && obj == "" && Object.keys(obj).length == 0));
    },
    /*
     * 將字元轉換為數字
     * 
     * @param str:數字字串
     * @return 返回數字
     */
    parseInt(str) {
        return parseInt(str, 10);
    },
    /*
     * 去除字串兩邊的空格
     */
    trim(str) {
        if (str == null || str == "") return;
        return str.replace(/(^\s*)|(\s*$)/g, '');
    },
    /*
     * 去除字串全部空格
     */
    trimAll(str) {
        if (this.isNull(str)) return;
        return str.replace(/\s/g, '');
    },
    /**
     * Map轉為Object物件
     */
    mapToObject(map) {
        let obj = Object.create(null);
        for (let [k, v] of map) {
            obj[k] = v;
        }
        return obj;
    },
    /**
     * Object物件轉為Map
     */
    objectToMap(obj) {
        let map = new Map();
        for (let k of Object.keys(obj)) {
            map.set(k, obj[k]);
        }
        return map;
    },
    /**
     * Map轉為Json
     */
    mapToJson(map) {
        return JSON.stringify(this.mapToObject(map));
    },
    /**
     * Json轉為Map
     */
    jsonToMap(json) {
        return this.objectToMap(JSON.parse(json));
    },
    /*
     * 獲得預設日期,格式為:yyyy-MM-dd
     */
    getDefaultDate(date = new Date()) {
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();

        return [year, month, day].map(this.digit).join("-");
    },
    /*
     * 獲得預設時間,格式為:yyyy-MM-dd HH:mm:ss
     */
    getDefaultTime(date = new Date()) {
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();
        let hour = date.getHours();
        let minute = date.getMinutes();
        let second = date.getSeconds();

        return [year, month, day].map(this.digit).join("-") + " " + [hour, minute, second].map(this.digit).join(":");
    },

    /**
     * 將日期字串轉換為陣列
     * 
     * @param dateStr:日期字串 格式為yyyy-MM-dd HH:mm:ss或者yyyy/MM/dd HH:mm:ss
     * @return 返回字串陣列
     */
    formatDateStrToArray(dateStr) {
        dateStr = dateStr.replace(/(\-)|(\:)|(\s)|(\/)/g, ',');
        return dateStr.split(",");
    },
    /**
     * 格式化日期字串為日期物件
     * 
     * @param dateStr:日期字串,支援yyyy-MM-dd HH:mm:ss或者yyyy/MM/dd HH:mm:ss
     * @return 返回日期物件
     */
    formatDateStrToDate: function (dateStr) {
        if (this.isNull(dateStr)) return;
        dateStr = dateStr.replace(/\-/g, "/");
        return new Date(dateStr);
    },
    /**
     * 將日期物件轉為指定日期格式的字串
     * 
     * @param date:要轉換的日期
     * @param formatStr:需要格式化的字串,如yyyy/MM/dd HH:mm:ss,預設是yyyy-MM-dd
     * @return 返回指定格式的日期字串
     */
    formatDateToDateStr(date, formatStr = "yyyy-MM-dd") {
        if ((!date) || new Date(date) == 'Invalid Date') {
            return null;
        }
        // 日期字串格式化
        let o = {
            "M+": date.getMonth() + 1, // 月
            "d+": date.getDate(), // 日
            "h+": (date.getHours() % 12) == 0 ? 12 : (date.getHours() % 12), // 12小時制
            "H+": date.getHours(), // 24小時制
            "m+": date.getMinutes(), // 分鐘
            "s+": date.getSeconds(), // 秒
            "q+": Math.floor((date.getMonth() + 3) / 3), //季度 
            "S": date.getMilliseconds(), //毫秒 
        };
        if (/(y+)/.test(formatStr)) {
            formatStr = formatStr.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (let k in o) {
            if (new RegExp("(" + k + ")").test(formatStr))
                formatStr = formatStr.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
        return formatStr;
    },

    /**
     * 獲得加減後的天數
     * 
     * @param date:需要操作的日期
     * @param n:加減日期的數量,可以是正負
     * @return 返回加減後的日期物件
     */
    getDiffDate(date, n) {
        date.setDate(date.getDate() + n);
        return date;
    },
    /**
     * 計算兩個日期之間相差的天數
     * @param {計算的開始日期} startDate 
     * @param {計算的結束日期} endDate 
     */
    getDiffDaysNumber(beginStr, endStr) {
        if (beginStr == null || beginStr == null) return 0;
        let startDate = this.formatDateStrToDate(beginStr);
        let endDate = this.formatDateStrToDate(endStr);
        if ((endDate.getTime() - startDate.getTime()) >= 0) {
            return (endDate.getTime() - startDate.getTime()) / (24 * 60 * 60 * 1000);
        } else {
            return -1;
        }
    },
    /**
     * 獲得兩個日期之間所有日期
     * 
     * @param start,開始時間,end:結束時間,可以是date和字串型別,字串支援yyyy-MM-dd
     * @return 返回日期字串陣列
     */
    getBetweenDateStr: function (beginStr, endStr) {
        let diffDates = [];
        let startDate = this.formatDateStrToDate(beginStr);
        let endDate = this.formatDateStrToDate(endStr);

        // 計算日期
        while (endDate.getTime() - startDate.getTime() >= 0) {
            let year = startDate.getFullYear();
            let month = startDate.getMonth().toString().length == 1 ? "0" + (startDate.getMonth() + 1).toString() : (startDate.getMonth() + 1);
            let day = startDate.getDate().toString().length == 1 ? "0" + startDate.getDate() : startDate.getDate();
            diffDates.push(year + "-" + month + "-" + day);
            startDate.setDate(startDate.getDate() + 1);
        }
        // 返回結果
        return diffDates;
    },
    /**
     * 判斷是否是閏年
     * 
     * @param y:年份
     * @return 返回true和false
     */
    isLeap: function (y) {
        return (y % 100 !== 0 && y % 4 === 0) || (y % 400 === 0);
    },
    /**
     * 根據年月日獲得當天是周幾
     * 
     * @param date:日期
     * @param type:為0則返回週一,週二這樣的漢字,為1返回1,2,3,4
     * @return 返回周幾
     */
    getWeekOfDate: function (date, type = 0) {
        if (this.isNull(date)) return;
        let weekStr = null;
        if (type) {
            weekStr = new Array("週日", "週一", "週二", "週三", "週四", "週五", "週六")[date.getDay()];
        } else {
            weekStr = new Array("7", "1", "2", "3", "4", "5", "6")[date.getDay()];
        }
        // 返回結果
        return weekStr;

    },
    /**
     * 陣列中是否包含指定的字串
     * 
     * @param str:指定字串
     * @param array:查詢的陣列
     * @return 返回true和false
     */
    containInArray: function (str, array) {
        if (this.isNull(str) || this.isNull(array)) return;
        return array.includes(str);
    },
    /**
     * 獲得字串在陣列中出現位置
     * 
     * @param str:需要在陣列中查詢位置的字串
     * @param array:陣列
     * @return 返回位置
     */
    getIndexInArray: function (str, array) {
        if (this.isNull(str) || this.isNull(array)) return;
        return array.indexOf(str);
    }

}