Unique ID that gets a date in specific format?

后端 未结 2 534
滥情空心
滥情空心 2021-01-26 02:33

I have code that will generate a random unique id.. but is there a way I can edit this code so that it grabs a date in a specific way like yyyy-mm-dd-0001. the last 4 digits I w

2条回答
  •  余生分开走
    2021-01-26 03:14

    If you are asking for a way to keep track of how many times an ID is generated by all your site visitors using javascript alone then, no it is not possible without tying in some back end to keep track. However, the following code will do what you ask per visitor.

    jsfiddle

    var ttlIds = 0;
    
    function guidGenerator() {
        var S4 = function () {
            return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        }
        return (S4() + S4() + S4());
    
    }
    
    function generateID() {
    
        var TheTextBox = document.getElementById("generateidtxt");
        TheTextBox.value = TheTextBox.value + guidGenerator().toString().toUpperCase();
        //document.getElementById("generateid").disabled=true; 
    
        ttlIds++;
        if(ttlIds < 10){
            ttlIds_formatted = '000'+ttlIds;
        }else if(ttlIds < 100){
            ttlIds_formatted = '00'+ttlIds;
        }else if(ttlIds < 1000){
            ttlIds_formatted = '0'+ttlIds;    
        }
        d = new Date();
        var funkydate = d.getFullYear() +'-' + (d.getMonth()+1) + '-' + d.getDate() + '-' + ttlIds_formatted;
        document.getElementById("funkydate").value = funkydate;
    
    }
    

提交回复
热议问题