我想在nodejs中自動生成像“DC” yaer mounth 4位數的ID。
我正在使用節點 js 創建一個 api 來連接到我使用 phpmyadmin 的資料庫 我想創建一個像 AB22020001 這樣的 ID 但現在我能做的就是創建一個像 AB2202 這樣的 ID。后面的號碼不知道怎么打。我的身份證由 2 個字母組成,最后 2 位年份和月份,其他 4 位數字從 0001 到 9999。當新的月份開始時,最后 4 位數字又從 00001 開始計數。
在我的代碼中
let date_ob = new Date();
let year = date_ob.getFullYear();
let yaer_today = year.toString().substring(2)
let month = ("0" (date_ob.getMonth() 1)).slice(-2);
const ID = 'AB' yaer_today month
console.log(ID)
uj5u.com熱心網友回復:
不確定這是否是您的確切要求,它將根據您的需要增加 ID 系列,并在月份更改后重置為“0001”。但是你沒有告訴如果計數器在同一個月達到“9999”會發生什么。
function generateId() {
let id = getLastId();
let finalId = ''
if (!id) {
let alpha_series = "AB";
let year_now = new Date().getFullYear().toString();
year_now = year_now.slice(-2);
let month_now = new Date().getMonth() 1;
month_now = month_now < 10 ? "0" month_now : month_now;
let incrementer = "0001";
finalId = alpha_series year_now month_now incrementer;
} else {
let alpha_series = id.slice(0, 2);
let year_id = id.slice(2, 4);
let year_now = new Date().getFullYear().toString();
year_now = year_now.slice(-2);
year_id = year_id == year_now ? year_id : year_now;
let month_id = id.slice(4, 6);
let month_now = new Date().getMonth() 1;
month_now = month_now < 10 ? "0" month_now : month_now;
let final_month_id = month_id == month_now ? month_id : month_now;
let lastIdIncrement = parseInt(id.slice(-4));
let incrementer = addLeadingZeros((lastIdIncrement 1).toString());
incrementer = month_id == month_now ? incrementer : "0001";
finalId = alpha_series year_id final_month_id incrementer;
}
//insert the id in db.
return finalId;
}
function getLastId() {
// query to get last inserted id
let id = null; //replace this with actual id retrieved from DB.
if (id)
return id;
else
return null;
}
function addLeadingZeros(id) {
if (id.length < 4) {
var noneZeroEcode = Number(id).toString();
var pad = "0000";
var id = pad.substring(0, pad.length - noneZeroEcode.length) noneZeroEcode;
return id;
} else {
return id;
}
}
console.log(generateId());
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/432986.html
