js 根据时间生成唯一订单号

    xiaoxiao2022-07-07  202

    一般做唯一编号的时候,可以使用guid或者uuid的包直接生成,但是我希望唯一编号能够反应生成的时间信息,所以就准备使用日期+随机值来构造,代码如下:

    const tradeNo = function () { const now = new Date() const year = now.getFullYear(); let month = now.getMonth() + 1; let day = now.getDate(); let hour = now.getHours(); let minutes = now.getMinutes(); let seconds = now.getSeconds(); String(month).length < 2 ? (month = Number("0" + month)) : month; String(day).length < 2 ? (day = Number("0" + day)) : day; String(hour).length < 2 ? (hour = Number("0" + hour)) : hour; String(minutes).length < 2 ? (minutes = Number("0" + minutes)) : minutes; String(seconds).length < 2 ? (seconds = Number("0" + seconds)) : seconds; const yyyyMMddHHmmss = `${year}${month}${day}${hour}${minutes}${seconds}`; return yyyyMMddHHmmss + '_' + Math.random().toString(36).substr(2, 9); }; // 使用 tradeNo();

    生成的唯一订单号举例如下:原则上是不会重复的。

    2019522203532_2lubccbkd 2019522203540_a297n7f9g 2019522203549_hr013qzes
    最新回复(0)