js 格式化时间、字符串指定长度、随机字符串

格式化字符串长度

方法

    function formatWidth(str, width){
        str += ''
        if(str.length<width) 
            return formatWidth('0'+str, width)
        else
            return str
    }

测试代码

        a = 13
        console.log(a,formatWidth(a,6))
        a = 032
        console.log(a,formatWidth(a,6))
        a = 1332413244244
        console.log(a,formatWidth(a,6))

运行结果

获取格式化时间字符串

方法

    function timeFormat(inTime, formatStr, getDate){
        formatStr = formatStr || 'Y-M-D H:m:S'
        let weeks = ['','','','','','','']
        let formater = {
            Y: inTime.getFullYear(),
            M: formatWidth(inTime.getMonth()+1,2),
            D: formatWidth(inTime.getDate(),2),
            H: formatWidth(inTime.getHours(),2),
            m: formatWidth(inTime.getMinutes(),2),
            S: formatWidth(inTime.getSeconds(),2),
            W: '星期'+weeks[inTime.getDay()]
        }
        for(let i in formater)
            formatStr = formatStr.replace(i, formater[i])
        return getDate ? new Date(formatStr) : formatStr        
    }

测试代码

        console.dir(timeFormat(new Date(), 'Y-M-D H:m:S'))
        console.dir(timeFormat(new Date(), 'YMDHmS'))
        console.dir(timeFormat(new Date(), 'Y H:m:S'))
        console.dir(timeFormat(new Date(), 'Y-M-D'))

测试结果

随机字符串

方法

    function randomString(len) {
      len = len || 32;
      var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
      var maxPos = $chars.length;
      var pwd = '';
      for (i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
      }
      return pwd;
    }

测试代码

        console.log(randomString(32))
        console.log(randomString(32))
        console.log(randomString(32))
        console.log(randomString(32))

测试结果

原文地址:https://www.cnblogs.com/lurenjia1994/p/9646330.html