js 如何在数字前面自动补零,生成序列号、单据号
//获取指定位数的序号(如:003) var GetSerialNum = function(num,length){ var serialNum = (Array(length).join(0) + num).slice(-length); console.log(serialNum); return serialNum; } //获取指定日期格式的日期 var getFullDataStr = function (dateformat) { var dateStr = ""; var mydate = new Date(); var year = mydate.getFullYear(); //console.log(typeof(year)); 可输出值的类型 var month = (mydate.getMonth() + 1) < 10 ? '0' + (mydate.getMonth() + 1) : (mydate.getMonth() + 1) + ''; var day = mydate.getDate() < 10 ? '0' + mydate.getDate() : mydate.getDate() + ''; var hours = mydate.getHours() < 10 ? '0' + mydate.getHours() : mydate.getHours() + ''; var minutes = mydate.getMinutes() < 10 ? '0' + mydate.getMinutes() : mydate.getMinutes() + ''; var seconds = mydate.getSeconds() < 10 ? '0' + mydate.getSeconds() : mydate.getSeconds() + ''; //var minseconds = mydate.getMilliseconds().toString().substring(0,2); var minseconds = mydate.getMilliseconds().toString(); if (dateformat.toLowerCase() == "yyyy") { dateStr = year; } else if (dateformat.toLowerCase() == "yyyymm") { dateStr = year + month; } else if (dateformat.toLowerCase() == "yyyymmdd") { dateStr = year + month + day; } else if (dateformat.toLowerCase() == "yyyymmddhhmmss") { dateStr = year + month + day + hours + minutes + seconds; } else if (dateformat.toLowerCase() == "yymmddhhmmss") { dateStr = year.toString().substring(2, 4) + month + day + hours + minutes + seconds; } else if (dateformat.toLowerCase() == "yyyymmddhhmmssms") { dateStr = year + month + day + hours + minutes + seconds + minseconds; } else if (dateformat.toLowerCase() == "yymmddhhmmssms") { dateStr = year.toString().substring(2, 4) + month + day + hours + minutes + seconds + minseconds;; } else { dateStr = year + month + day; } return dateStr; } //获取单据的序列号 var GetSerialBillNo = function(num,length,format){ //获取序号值 var serialNum = GetSerialNum(num,length); //获取日期字符串 var serialdate = getFullDataStr("yyyymmdd"); //拼接对应单号 var serialBillNo =serialdate+ serialNum; console.log(serialBillNo); return serialBillNo; }
<body> <button onClick="GetSerialNum(5,4)">获取序号值</button> <button onClick="GetSerialBillNo(8,6,'yyyymmdd')">获取单据号</button> </body>
根据上面输出的结果
0005
000008
20201201000008
注意:真正调用的时候,自己传递函数的参数值,记得把打印去掉
参考网址:
平时多记记,到用时才能看看,记录你的进步,分享你的成果