quiero generar automáticamente una identificación como "DC" + yaer + mounth + 4 dígitos en nodejs.
Estoy usando el nodo js para crear una API para conectarme a la base de datos que uso phpmyadmin Quiero crear una identificación como AB22020001 Pero ahora todo lo que puedo hacer es crear una identificación como AB2202. No sé cómo hacer el número después. Mi identificación consta de 2 letras, los últimos 2 dígitos del año y el mes, y los otros 4 dígitos van desde 0001 hasta 9999. Cuando comienza un nuevo mes, los últimos 4 dígitos comienzan a contar en 00001 nuevamente.
en mi codigo
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)
No estoy seguro de si este es su requisito exacto. Incrementará la serie de ID según sus necesidades y se restablecerá a "0001" una vez que cambie el mes. pero no dijo qué sucede si el contador llega a "9999" en el mismo mes.
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());